blob: d1bbfa9033cef4ae4ca9f4fde6930518e0ed03e8 [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
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800156SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700157 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800158 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700159 mTransactionPending(false),
160 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700161 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700162 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700163 mRepaintEverything(0),
Kalle Raitaa099a242017-01-11 11:17:29 -0800164 mHwcServiceName(getHwcServiceName()),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800165 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800166 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800167 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800168 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800169 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800170 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800171 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700172 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700173 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700174 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700175 mDebugInSwapBuffers(0),
176 mLastSwapBufferTime(0),
177 mDebugInTransaction(0),
178 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700179 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700180 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800181 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000182 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700183 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700184 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700185 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800186 mHasPoweredOff(false),
187 mFrameBuckets(),
188 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700189 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800190 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700191 mVrFlingerRequestsDisplay(false),
192 mMainThreadId(std::this_thread::get_id()),
193 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800195 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800196
197 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
198 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
199
200 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
201 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
202
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800203 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
204 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700206 useContextPriority = getBool< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::useContextPriority>(false);
208
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700209 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
210 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
211
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700212 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
213 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
214
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800215 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
216 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
217
Steven Thomas050b2c82017-03-06 11:45:16 -0800218 // Vr flinger is only enabled on Daydream ready devices.
219 useVrFlinger = getBool< ISurfaceFlingerConfigs,
220 &ISurfaceFlingerConfigs::useVrFlinger>(false);
221
Fabien Sanglard1971b632017-03-10 14:50:03 -0800222 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
223 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
224
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600225 hasWideColorDisplay =
226 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
227
Saurabh Shahf4174532017-07-13 10:45:07 -0700228 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
229
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230 // debugging stuff...
231 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700232
Mathias Agopianb4b17302013-03-20 18:36:41 -0700233 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700234 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700235
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236 property_get("debug.sf.showupdates", value, "0");
237 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700238
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239 property_get("debug.sf.ddms", value, "0");
240 mDebugDDMS = atoi(value);
241 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700242 if (!startDdmConnection()) {
243 // start failed, and DDMS debugging not enabled
244 mDebugDDMS = 0;
245 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700246 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700247 ALOGI_IF(mDebugRegion, "showupdates enabled");
248 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700249
250 property_get("debug.sf.disable_backpressure", value, "0");
251 mPropagateBackpressure = !atoi(value);
252 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700253
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800254 property_get("debug.sf.enable_hwc_vds", value, "0");
255 mUseHwcVirtualDisplays = atoi(value);
256 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800257
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800258 property_get("ro.sf.disable_triple_buffer", value, "1");
259 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800260 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700261
Romain Guy11d63f42017-07-20 12:47:14 -0700262 // We should be reading 'persist.sys.sf.color_saturation' here
263 // but since /data may be encrypted, we need to wait until after vold
264 // comes online to attempt to read the property. The property is
265 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800266
267 if (useTrebleTestingOverride()) {
268 // Without the override SurfaceFlinger cannot connect to HIDL
269 // services that are not listed in the manifests. Considered
270 // deriving the setting from the set service name, but it
271 // would be brittle if the name that's not 'default' is used
272 // for production purposes later on.
273 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
274 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275}
276
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800277void SurfaceFlinger::onFirstRef()
278{
279 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800280}
281
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282SurfaceFlinger::~SurfaceFlinger()
283{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284}
285
Dan Stozac7014012014-02-14 15:03:43 -0800286void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800287{
288 // the window manager died on us. prepare its eulogy.
289
Andy McFadden13a082e2012-08-24 10:16:42 -0700290 // restore initial conditions (default device unblank, etc)
291 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800292
293 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700294 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800295}
296
Robert Carr1db73f62016-12-21 12:58:51 -0800297static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700298 status_t err = client->initCheck();
299 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800300 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800301 }
Robert Carr1db73f62016-12-21 12:58:51 -0800302 return nullptr;
303}
304
305sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
306 return initClient(new Client(this));
307}
308
309sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
310 const sp<IGraphicBufferProducer>& gbp) {
311 if (authenticateSurfaceTexture(gbp) == false) {
312 return nullptr;
313 }
314 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
315 if (layer == nullptr) {
316 return nullptr;
317 }
318
319 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320}
321
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700322sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
323 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700324{
325 class DisplayToken : public BBinder {
326 sp<SurfaceFlinger> flinger;
327 virtual ~DisplayToken() {
328 // no more references, this display must be terminated
329 Mutex::Autolock _l(flinger->mStateLock);
330 flinger->mCurrentState.displays.removeItem(this);
331 flinger->setTransactionFlags(eDisplayTransactionNeeded);
332 }
333 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700334 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700335 : flinger(flinger) {
336 }
337 };
338
339 sp<BBinder> token = new DisplayToken(this);
340
341 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700342 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700343 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700344 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700345 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700346 return token;
347}
348
Jesse Hall6c913be2013-08-08 12:15:49 -0700349void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
350 Mutex::Autolock _l(mStateLock);
351
352 ssize_t idx = mCurrentState.displays.indexOfKey(display);
353 if (idx < 0) {
354 ALOGW("destroyDisplay: invalid display token");
355 return;
356 }
357
358 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
359 if (!info.isVirtualDisplay()) {
360 ALOGE("destroyDisplay called for non-virtual display");
361 return;
362 }
Irvelffc9efc2016-07-27 15:16:37 -0700363 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700364 mCurrentState.displays.removeItemsAt(idx);
365 setTransactionFlags(eDisplayTransactionNeeded);
366}
367
Jesse Hall692c7232012-11-08 15:41:56 -0800368void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800369 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800370 ALOGW_IF(mBuiltinDisplays[type],
371 "Overwriting display token for display type %d", type);
372 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800373 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700374 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800375 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700376 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800377}
378
Mathias Agopiane57f2922012-08-09 16:29:12 -0700379sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700380 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700381 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
382 return NULL;
383 }
Jesse Hall692c7232012-11-08 15:41:56 -0800384 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700385}
386
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800387void SurfaceFlinger::bootFinished()
388{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700389 if (mStartPropertySetThread->join() != NO_ERROR) {
390 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800391 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800392 const nsecs_t now = systemTime();
393 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000394 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700395
396 // wait patiently for the window manager death
397 const String16 name("window");
398 sp<IBinder> window(defaultServiceManager()->getService(name));
399 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700400 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700401 }
402
Steven Thomas050b2c82017-03-06 11:45:16 -0800403 if (mVrFlinger) {
404 mVrFlinger->OnBootFinished();
405 }
406
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700407 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700408 // formerly we would just kill the process, but we now ask it to exit so it
409 // can choose where to stop the animation.
410 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700411
412 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
413 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
414 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700415
Thierry Strudel2924d012017-08-14 15:19:37 -0700416 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700417 readPersistentProperties();
418 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700419 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800420}
421
Mathias Agopian3f844832013-08-07 21:24:32 -0700422void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700423 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700424 RenderEngine& engine;
425 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700426 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700427 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
428 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700429 }
430 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700431 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700432 return true;
433 }
434 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700435 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700436}
437
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438class DispSyncSource : public VSyncSource, private DispSync::Callback {
439public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700440 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000441 const char* name) :
442 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700443 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700444 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000445 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
446 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700447 mDispSync(dispSync),
448 mCallbackMutex(),
449 mCallback(),
450 mVsyncMutex(),
451 mPhaseOffset(phaseOffset),
452 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700453
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454 virtual ~DispSyncSource() {}
455
456 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700457 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000459 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700460 static_cast<DispSync::Callback*>(this));
461 if (err != NO_ERROR) {
462 ALOGE("error registering vsync callback: %s (%d)",
463 strerror(-err), err);
464 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700465 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700466 } else {
467 status_t err = mDispSync->removeEventListener(
468 static_cast<DispSync::Callback*>(this));
469 if (err != NO_ERROR) {
470 ALOGE("error unregistering vsync callback: %s (%d)",
471 strerror(-err), err);
472 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700473 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700475 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700476 }
477
478 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700479 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 mCallback = callback;
481 }
482
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700483 virtual void setPhaseOffset(nsecs_t phaseOffset) {
484 Mutex::Autolock lock(mVsyncMutex);
485
486 // Normalize phaseOffset to [0, period)
487 auto period = mDispSync->getPeriod();
488 phaseOffset %= period;
489 if (phaseOffset < 0) {
490 // If we're here, then phaseOffset is in (-period, 0). After this
491 // operation, it will be in (0, period)
492 phaseOffset += period;
493 }
494 mPhaseOffset = phaseOffset;
495
496 // If we're not enabled, we don't need to mess with the listeners
497 if (!mEnabled) {
498 return;
499 }
500
501 // Remove the listener with the old offset
502 status_t err = mDispSync->removeEventListener(
503 static_cast<DispSync::Callback*>(this));
504 if (err != NO_ERROR) {
505 ALOGE("error unregistering vsync callback: %s (%d)",
506 strerror(-err), err);
507 }
508
509 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000510 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511 static_cast<DispSync::Callback*>(this));
512 if (err != NO_ERROR) {
513 ALOGE("error registering vsync callback: %s (%d)",
514 strerror(-err), err);
515 }
516 }
517
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518private:
519 virtual void onDispSyncEvent(nsecs_t when) {
520 sp<VSyncSource::Callback> callback;
521 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700522 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523 callback = mCallback;
524
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700525 if (mTraceVsync) {
526 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700527 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700528 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700529 }
530
531 if (callback != NULL) {
532 callback->onVSyncEvent(when);
533 }
534 }
535
Tim Murray4a4e4a22016-04-19 16:29:23 +0000536 const char* const mName;
537
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700538 int mValue;
539
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700540 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700541 const String8 mVsyncOnLabel;
542 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700543
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700545
546 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700547 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700548
549 Mutex mVsyncMutex; // Protects the following
550 nsecs_t mPhaseOffset;
551 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552};
553
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700554class InjectVSyncSource : public VSyncSource {
555public:
556 InjectVSyncSource() {}
557
558 virtual ~InjectVSyncSource() {}
559
560 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
561 std::lock_guard<std::mutex> lock(mCallbackMutex);
562 mCallback = callback;
563 }
564
565 virtual void onInjectSyncEvent(nsecs_t when) {
566 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700567 if (mCallback) {
568 mCallback->onVSyncEvent(when);
569 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700570 }
571
572 virtual void setVSyncEnabled(bool) {}
573 virtual void setPhaseOffset(nsecs_t) {}
574
575private:
576 std::mutex mCallbackMutex; // Protects the following
577 sp<VSyncSource::Callback> mCallback;
578};
579
Wei Wangf9b05ee2017-07-19 20:59:39 -0700580// Do not call property_set on main thread which will be blocked by init
581// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700582void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700583 ALOGI( "SurfaceFlinger's main thread ready to run. "
584 "Initializing graphics H/W...");
585
Thierry Strudel2924d012017-08-14 15:19:37 -0700586 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900587
Steven Thomasb02664d2017-07-26 18:48:28 -0700588 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800589
Steven Thomasb02664d2017-07-26 18:48:28 -0700590 // start the EventThread
591 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
592 vsyncPhaseOffsetNs, true, "app");
593 mEventThread = new EventThread(vsyncSrc, *this, false);
594 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
595 sfVsyncPhaseOffsetNs, true, "sf");
596 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
597 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800598
Steven Thomasb02664d2017-07-26 18:48:28 -0700599 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
600 struct sched_param param = {0};
601 param.sched_priority = 2;
602 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
603 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
604 }
605 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
606 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800607 }
608
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 // Get a RenderEngine for the given display / config (can't fail)
Chia-I Wud4d9c6f2017-11-09 16:55:31 -0800610 mRenderEngine = RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
Steven Thomasb02664d2017-07-26 18:48:28 -0700611 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Chia-I Wud4d9c6f2017-11-09 16:55:31 -0800612 LOG_ALWAYS_FATAL_IF(mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700613
614 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
615 "Starting with vr flinger active is not currently supported.");
616 mHwc.reset(new HWComposer(mHwcServiceName));
617 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800618
Steven Thomas050b2c82017-03-06 11:45:16 -0800619 if (useVrFlinger) {
620 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700621 // This callback is called from the vr flinger dispatch thread. We
622 // need to call signalTransaction(), which requires holding
623 // mStateLock when we're not on the main thread. Acquiring
624 // mStateLock from the vr flinger dispatch thread might trigger a
625 // deadlock in surface flinger (see b/66916578), so post a message
626 // to be handled on the main thread instead.
627 sp<LambdaMessage> message = new LambdaMessage([=]() {
628 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
629 mVrFlingerRequestsDisplay = requestDisplay;
630 signalTransaction();
631 });
632 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800633 };
634 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800635 mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
636 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800637 if (!mVrFlinger) {
638 ALOGE("Failed to start vrflinger");
639 }
640 }
641
Jamie Gennisd1700752013-10-14 12:22:52 -0700642 mEventControlThread = new EventControlThread(this);
643 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
644
Mathias Agopian92a979a2012-08-02 18:32:23 -0700645 // initialize our drawing state
646 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700647
Andy McFadden13a082e2012-08-24 10:16:42 -0700648 // set initial conditions (e.g. unblank default device)
649 initializeDisplays();
650
Dan Stoza4e637772016-07-28 13:31:51 -0700651 mRenderEngine->primeCache();
652
Wei Wangf9b05ee2017-07-19 20:59:39 -0700653 // Inform native graphics APIs whether the present timestamp is supported:
654 if (getHwComposer().hasCapability(
655 HWC2::Capability::PresentFenceIsNotReliable)) {
656 mStartPropertySetThread = new StartPropertySetThread(false);
657 } else {
658 mStartPropertySetThread = new StartPropertySetThread(true);
659 }
660
661 if (mStartPropertySetThread->Start() != NO_ERROR) {
662 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800663 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800664
Dan Stoza9e56aa02015-11-02 13:00:03 -0800665 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700666}
667
Romain Guy11d63f42017-07-20 12:47:14 -0700668void SurfaceFlinger::readPersistentProperties() {
669 char value[PROPERTY_VALUE_MAX];
670
671 property_get("persist.sys.sf.color_saturation", value, "1.0");
672 mSaturation = atof(value);
673 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100674
675 property_get("persist.sys.sf.native_mode", value, "0");
676 mForceNativeColorMode = atoi(value) == 1;
677 if (mForceNativeColorMode) {
678 ALOGV("Forcing native color mode");
679 }
Romain Guy11d63f42017-07-20 12:47:14 -0700680}
681
Mathias Agopiana67e4182012-06-19 17:26:12 -0700682void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800683 // Start boot animation service by setting a property mailbox
684 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700685 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800686 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700687 if (mStartPropertySetThread->join() != NO_ERROR) {
688 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800689 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700690}
691
Mathias Agopian875d8e12013-06-07 15:35:48 -0700692size_t SurfaceFlinger::getMaxTextureSize() const {
693 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700694}
695
Mathias Agopian875d8e12013-06-07 15:35:48 -0700696size_t SurfaceFlinger::getMaxViewportDims() const {
697 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700698}
699
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800700// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800701
Jamie Gennis582270d2011-08-17 18:19:00 -0700702bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800703 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800704 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800705 return authenticateSurfaceTextureLocked(bufferProducer);
706}
707
708bool SurfaceFlinger::authenticateSurfaceTextureLocked(
709 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800710 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700711 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800712}
713
Brian Anderson6b376712017-04-04 10:51:39 -0700714status_t SurfaceFlinger::getSupportedFrameTimestamps(
715 std::vector<FrameEvent>* outSupported) const {
716 *outSupported = {
717 FrameEvent::REQUESTED_PRESENT,
718 FrameEvent::ACQUIRE,
719 FrameEvent::LATCH,
720 FrameEvent::FIRST_REFRESH_START,
721 FrameEvent::LAST_REFRESH_START,
722 FrameEvent::GPU_COMPOSITION_DONE,
723 FrameEvent::DEQUEUE_READY,
724 FrameEvent::RELEASE,
725 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700726 ConditionalLock _l(mStateLock,
727 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700728 if (!getHwComposer().hasCapability(
729 HWC2::Capability::PresentFenceIsNotReliable)) {
730 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
731 }
732 return NO_ERROR;
733}
734
Dan Stoza7f7da322014-05-02 15:26:25 -0700735status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
736 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700737 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700738 return BAD_VALUE;
739 }
740
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500741 if (!display.get())
742 return NAME_NOT_FOUND;
743
Jesse Hall692c7232012-11-08 15:41:56 -0800744 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700745 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800746 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700747 type = i;
748 break;
749 }
750 }
751
752 if (type < 0) {
753 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700754 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700755
Mathias Agopian8b736f12012-08-13 17:54:26 -0700756 // TODO: Not sure if display density should handled by SF any longer
757 class Density {
758 static int getDensityFromProperty(char const* propName) {
759 char property[PROPERTY_VALUE_MAX];
760 int density = 0;
761 if (property_get(propName, property, NULL) > 0) {
762 density = atoi(property);
763 }
764 return density;
765 }
766 public:
767 static int getEmuDensity() {
768 return getDensityFromProperty("qemu.sf.lcd_density"); }
769 static int getBuildDensity() {
770 return getDensityFromProperty("ro.sf.lcd_density"); }
771 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700772
Dan Stoza7f7da322014-05-02 15:26:25 -0700773 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700774
Steven Thomas6d8110b2017-08-31 18:24:21 -0700775 ConditionalLock _l(mStateLock,
776 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800777 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700778 DisplayInfo info = DisplayInfo();
779
Dan Stoza9e56aa02015-11-02 13:00:03 -0800780 float xdpi = hwConfig->getDpiX();
781 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700782
783 if (type == DisplayDevice::DISPLAY_PRIMARY) {
784 // The density of the device is provided by a build property
785 float density = Density::getBuildDensity() / 160.0f;
786 if (density == 0) {
787 // the build doesn't provide a density -- this is wrong!
788 // use xdpi instead
789 ALOGE("ro.sf.lcd_density must be defined as a build property");
790 density = xdpi / 160.0f;
791 }
792 if (Density::getEmuDensity()) {
793 // if "qemu.sf.lcd_density" is specified, it overrides everything
794 xdpi = ydpi = density = Density::getEmuDensity();
795 density /= 160.0f;
796 }
797 info.density = density;
798
799 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700800 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000801 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700802 } else {
803 // TODO: where should this value come from?
804 static const int TV_DENSITY = 213;
805 info.density = TV_DENSITY / 160.0f;
806 info.orientation = 0;
807 }
808
Dan Stoza9e56aa02015-11-02 13:00:03 -0800809 info.w = hwConfig->getWidth();
810 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 info.xdpi = xdpi;
812 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800813 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900814 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815
Andy McFadden91b2ca82014-06-13 14:04:23 -0700816 // This is how far in advance a buffer must be queued for
817 // presentation at a given time. If you want a buffer to appear
818 // on the screen at time N, you must submit the buffer before
819 // (N - presentationDeadline).
820 //
821 // Normally it's one full refresh period (to give SF a chance to
822 // latch the buffer), but this can be reduced by configuring a
823 // DispSync offset. Any additional delays introduced by the hardware
824 // composer or panel must be accounted for here.
825 //
826 // We add an additional 1ms to allow for processing time and
827 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800829 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700830
831 // All non-virtual displays are currently considered secure.
832 info.secure = true;
833
Michael Wright28f24d02016-07-12 13:30:53 -0700834 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 }
836
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 return NO_ERROR;
838}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700839
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800840status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700841 DisplayStatInfo* stats) {
842 if (stats == NULL) {
843 return BAD_VALUE;
844 }
845
846 // FIXME for now we always return stats for the primary display
847 memset(stats, 0, sizeof(*stats));
848 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
849 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
850 return NO_ERROR;
851}
852
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700853int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800854 if (display == NULL) {
855 ALOGE("%s : display is NULL", __func__);
856 return BAD_VALUE;
857 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700858
859 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700860 if (device != NULL) {
861 return device->getActiveConfig();
862 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700863
Dan Stoza24a42e92015-03-09 10:04:11 -0700864 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700865}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700866
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700867void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
868 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
869 this);
870 int32_t type = hw->getDisplayType();
871 int currentMode = hw->getActiveConfig();
872
873 if (mode == currentMode) {
874 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
875 return;
876 }
877
878 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
879 ALOGW("Trying to set config for virtual display");
880 return;
881 }
882
883 hw->setActiveConfig(mode);
884 getHwComposer().setActiveConfig(type, mode);
885}
886
887status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
888 class MessageSetActiveConfig: public MessageBase {
889 SurfaceFlinger& mFlinger;
890 sp<IBinder> mDisplay;
891 int mMode;
892 public:
893 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
894 int mode) :
895 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
896 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700897 Vector<DisplayInfo> configs;
898 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700899 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700900 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700901 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700902 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700903 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700904 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
905 if (hw == NULL) {
906 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700907 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700908 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
909 ALOGW("Attempt to set active config = %d for virtual display",
910 mMode);
911 } else {
912 mFlinger.setActiveConfigInternal(hw, mMode);
913 }
914 return true;
915 }
916 };
917 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
918 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700919 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700920}
Michael Wright28f24d02016-07-12 13:30:53 -0700921status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
922 Vector<android_color_mode_t>* outColorModes) {
923 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
924 return BAD_VALUE;
925 }
926
927 if (!display.get()) {
928 return NAME_NOT_FOUND;
929 }
930
931 int32_t type = NAME_NOT_FOUND;
932 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
933 if (display == mBuiltinDisplays[i]) {
934 type = i;
935 break;
936 }
937 }
938
939 if (type < 0) {
940 return type;
941 }
942
Steven Thomas6d8110b2017-08-31 18:24:21 -0700943 std::vector<android_color_mode_t> modes;
944 {
945 ConditionalLock _l(mStateLock,
946 std::this_thread::get_id() != mMainThreadId);
947 modes = getHwComposer().getColorModes(type);
948 }
Michael Wright28f24d02016-07-12 13:30:53 -0700949 outColorModes->clear();
950 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
951
952 return NO_ERROR;
953}
954
955android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700956 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700957 if (device != nullptr) {
958 return device->getActiveColorMode();
959 }
960 return static_cast<android_color_mode_t>(BAD_VALUE);
961}
962
963void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
964 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700965 int32_t type = hw->getDisplayType();
966 android_color_mode_t currentMode = hw->getActiveColorMode();
967
968 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700969 return;
970 }
971
972 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
973 ALOGW("Trying to set config for virtual display");
974 return;
975 }
976
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600977 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
978 hw->getDisplayType());
979
Michael Wright28f24d02016-07-12 13:30:53 -0700980 hw->setActiveColorMode(mode);
981 getHwComposer().setActiveColorMode(type, mode);
982}
983
984
985status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
986 android_color_mode_t colorMode) {
987 class MessageSetActiveColorMode: public MessageBase {
988 SurfaceFlinger& mFlinger;
989 sp<IBinder> mDisplay;
990 android_color_mode_t mMode;
991 public:
992 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
993 android_color_mode_t mode) :
994 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
995 virtual bool handler() {
996 Vector<android_color_mode_t> modes;
997 mFlinger.getDisplayColorModes(mDisplay, &modes);
998 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
999 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001000 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1001 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001002 return true;
1003 }
1004 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1005 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001006 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1007 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001008 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001009 ALOGW("Attempt to set active color mode %s %d for virtual display",
1010 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001011 } else {
1012 mFlinger.setActiveColorModeInternal(hw, mMode);
1013 }
1014 return true;
1015 }
1016 };
1017 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1018 postMessageSync(msg);
1019 return NO_ERROR;
1020}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001021
Svetoslavd85084b2014-03-20 10:28:31 -07001022status_t SurfaceFlinger::clearAnimationFrameStats() {
1023 Mutex::Autolock _l(mStateLock);
1024 mAnimFrameTracker.clearStats();
1025 return NO_ERROR;
1026}
1027
1028status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1029 Mutex::Autolock _l(mStateLock);
1030 mAnimFrameTracker.getStats(outStats);
1031 return NO_ERROR;
1032}
1033
Dan Stozac4f471e2016-03-24 09:31:08 -07001034status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1035 HdrCapabilities* outCapabilities) const {
1036 Mutex::Autolock _l(mStateLock);
1037
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001038 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001039 if (displayDevice == nullptr) {
1040 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1041 return BAD_VALUE;
1042 }
1043
1044 std::unique_ptr<HdrCapabilities> capabilities =
1045 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1046 if (capabilities) {
1047 std::swap(*outCapabilities, *capabilities);
1048 } else {
1049 return BAD_VALUE;
1050 }
1051
1052 return NO_ERROR;
1053}
1054
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001055status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001056 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1057 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001058
Chia-I Wu90f669f2017-10-05 14:24:41 -07001059 if (mInjectVSyncs == enable) {
1060 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001061 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001062
1063 if (enable) {
1064 ALOGV("VSync Injections enabled");
1065 if (mVSyncInjector.get() == nullptr) {
1066 mVSyncInjector = new InjectVSyncSource();
1067 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1068 }
1069 mEventQueue.setEventThread(mInjectorEventThread);
1070 } else {
1071 ALOGV("VSync Injections disabled");
1072 mEventQueue.setEventThread(mSFEventThread);
1073 }
1074
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001075 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001076 });
1077 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001078 return NO_ERROR;
1079}
1080
1081status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001082 Mutex::Autolock _l(mStateLock);
1083
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001084 if (!mInjectVSyncs) {
1085 ALOGE("VSync Injections not enabled");
1086 return BAD_VALUE;
1087 }
1088 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1089 ALOGV("Injecting VSync inside SurfaceFlinger");
1090 mVSyncInjector->onInjectSyncEvent(when);
1091 }
1092 return NO_ERROR;
1093}
1094
Kalle Raitaa099a242017-01-11 11:17:29 -08001095status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1096 IPCThreadState* ipc = IPCThreadState::self();
1097 const int pid = ipc->getCallingPid();
1098 const int uid = ipc->getCallingUid();
1099 if ((uid != AID_SHELL) &&
1100 !PermissionCache::checkPermission(sDump, pid, uid)) {
1101 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1102 return PERMISSION_DENIED;
1103 }
1104
1105 // Try to acquire a lock for 1s, fail gracefully
1106 const status_t err = mStateLock.timedLock(s2ns(1));
1107 const bool locked = (err == NO_ERROR);
1108 if (!locked) {
1109 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1110 return TIMED_OUT;
1111 }
1112
1113 outLayers->clear();
1114 mCurrentState.traverseInZOrder([&](Layer* layer) {
1115 outLayers->push_back(layer->getLayerDebugInfo());
1116 });
1117
1118 mStateLock.unlock();
1119 return NO_ERROR;
1120}
1121
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001122// ----------------------------------------------------------------------------
1123
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001124sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1125 ISurfaceComposer::VsyncSource vsyncSource) {
1126 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1127 return mSFEventThread->createEventConnection();
1128 } else {
1129 return mEventThread->createEventConnection();
1130 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001131}
1132
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001133// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001134
1135void SurfaceFlinger::waitForEvent() {
1136 mEventQueue.waitMessage();
1137}
1138
1139void SurfaceFlinger::signalTransaction() {
1140 mEventQueue.invalidate();
1141}
1142
1143void SurfaceFlinger::signalLayerUpdate() {
1144 mEventQueue.invalidate();
1145}
1146
1147void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001148 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001149 mEventQueue.refresh();
1150}
1151
1152status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001153 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001154 return mEventQueue.postMessage(msg, reltime);
1155}
1156
1157status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001158 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001159 status_t res = mEventQueue.postMessage(msg, reltime);
1160 if (res == NO_ERROR) {
1161 msg->wait();
1162 }
1163 return res;
1164}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001165
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001166void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001167 do {
1168 waitForEvent();
1169 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001170}
1171
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001172void SurfaceFlinger::enableHardwareVsync() {
1173 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001174 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001175 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001176 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1177 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001178 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001179 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001180}
1181
Jesse Hall948fe0c2013-10-14 12:56:09 -07001182void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001183 Mutex::Autolock _l(mHWVsyncLock);
1184
Jesse Hall948fe0c2013-10-14 12:56:09 -07001185 if (makeAvailable) {
1186 mHWVsyncAvailable = true;
1187 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001188 // Hardware vsync is not currently available, so abort the resync
1189 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001190 return;
1191 }
1192
Dan Stoza9e56aa02015-11-02 13:00:03 -08001193 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1194 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195
1196 mPrimaryDispSync.reset();
1197 mPrimaryDispSync.setPeriod(period);
1198
1199 if (!mPrimaryHWVsyncEnabled) {
1200 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001201 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1202 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001203 mPrimaryHWVsyncEnabled = true;
1204 }
1205}
1206
Jesse Hall948fe0c2013-10-14 12:56:09 -07001207void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001208 Mutex::Autolock _l(mHWVsyncLock);
1209 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001210 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1211 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001212 mPrimaryDispSync.endResync();
1213 mPrimaryHWVsyncEnabled = false;
1214 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001215 if (makeUnavailable) {
1216 mHWVsyncAvailable = false;
1217 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218}
1219
Tim Murray4a4e4a22016-04-19 16:29:23 +00001220void SurfaceFlinger::resyncWithRateLimit() {
1221 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001222
1223 // No explicit locking is needed here since EventThread holds a lock while calling this method
1224 static nsecs_t sLastResyncAttempted = 0;
1225 const nsecs_t now = systemTime();
1226 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001227 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001228 }
Dan Stoza57164302017-05-08 14:03:54 -07001229 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001230}
1231
Steven Thomasb02664d2017-07-26 18:48:28 -07001232void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1233 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001234 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001235 // Ignore any vsyncs from a previous hardware composer.
1236 if (sequenceId != mComposerSequenceId) {
1237 return;
1238 }
1239
1240 int32_t type;
1241 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001242 return;
1243 }
1244
Jamie Gennisd1700752013-10-14 12:22:52 -07001245 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246
Jamie Gennisd1700752013-10-14 12:22:52 -07001247 { // Scope for the lock
1248 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001249 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001250 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001252 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001253
1254 if (needsHwVsync) {
1255 enableHardwareVsync();
1256 } else {
1257 disableHardwareVsync(false);
1258 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001259}
1260
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001261void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001262 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001263 *compositorTiming = mCompositorTiming;
1264}
1265
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001266void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001267 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001268 wp<IBinder> token = mBuiltinDisplays[type];
1269
1270 // All non-virtual displays are currently considered secure.
1271 const bool isSecure = true;
1272
1273 sp<IGraphicBufferProducer> producer;
1274 sp<IGraphicBufferConsumer> consumer;
1275 BufferQueue::createBufferQueue(&producer, &consumer);
1276
1277 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1278
1279 bool hasWideColorModes = false;
1280 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1281 for (android_color_mode_t colorMode : modes) {
1282 switch (colorMode) {
1283 case HAL_COLOR_MODE_DISPLAY_P3:
1284 case HAL_COLOR_MODE_ADOBE_RGB:
1285 case HAL_COLOR_MODE_DCI_P3:
1286 hasWideColorModes = true;
1287 break;
1288 default:
1289 break;
1290 }
1291 }
Romain Guy54f154a2017-10-24 21:40:32 +01001292 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001293 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
Chia-I Wuc670d502017-11-09 23:17:51 -08001294 token, fbs, producer, useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001295 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001296 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001297 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001298 defaultColorMode = HAL_COLOR_MODE_SRGB;
1299 }
1300 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001301 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001302
1303 // Add the primary display token to mDrawingState so we don't try to
1304 // recreate the DisplayDevice for the primary display.
1305 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1306
1307 // make the GLContext current so that we can create textures when creating
1308 // Layers (which may happens before we render something)
Chia-I Wu7f402902017-11-09 12:51:10 -08001309 hw->makeCurrent();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001310}
1311
Steven Thomasb02664d2017-07-26 18:48:28 -07001312void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1313 hwc2_display_t display, HWC2::Connection connection,
1314 bool primaryDisplay) {
1315 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1316 sequenceId, display,
1317 connection == HWC2::Connection::Connected ?
1318 "connected" : "disconnected",
1319 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001320
Steven Thomasb02664d2017-07-26 18:48:28 -07001321 // Only lock if we're not on the main thread. This function is normally
1322 // called on a hwbinder thread, but for the primary display it's called on
1323 // the main thread with the state lock already held, so don't attempt to
1324 // acquire it here.
1325 ConditionalLock lock(mStateLock,
1326 std::this_thread::get_id() != mMainThreadId);
1327
1328 if (primaryDisplay) {
1329 mHwc->onHotplug(display, connection);
1330 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1331 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001332 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001333 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001334 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001335 if (sequenceId != mComposerSequenceId) {
1336 return;
1337 }
1338 if (mHwc->isUsingVrComposer()) {
1339 ALOGE("External displays are not supported by the vr hardware composer.");
1340 return;
1341 }
1342 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001343 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001345 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001346 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001347 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1348 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001349 }
1350 setTransactionFlags(eDisplayTransactionNeeded);
1351
Andy McFadden9e9689c2012-10-10 18:17:51 -07001352 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001353 }
Mathias Agopian86303202012-07-24 22:46:10 -07001354}
1355
Steven Thomasb02664d2017-07-26 18:48:28 -07001356void SurfaceFlinger::onRefreshReceived(int sequenceId,
1357 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001358 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 if (sequenceId != mComposerSequenceId) {
1360 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001361 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001362 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001363}
1364
Dan Stoza9e56aa02015-11-02 13:00:03 -08001365void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001366 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001368 getHwComposer().setVsyncEnabled(disp,
1369 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001370}
1371
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001372// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001373void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001374 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001375 // Clear the drawing state so that the logic inside of
1376 // handleTransactionLocked will fire. It will determine the delta between
1377 // mCurrentState and mDrawingState and re-apply all changes when we make the
1378 // transition.
1379 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001380 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001381 mDisplays.clear();
1382}
1383
Steven Thomas050b2c82017-03-06 11:45:16 -08001384void SurfaceFlinger::updateVrFlinger() {
1385 if (!mVrFlinger)
1386 return;
1387 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1388 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001389 return;
1390 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001391
Steven Thomasb02664d2017-07-26 18:48:28 -07001392 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1393 ALOGE("Vr flinger is only supported for remote hardware composer"
1394 " service connections. Ignoring request to transition to vr"
1395 " flinger.");
1396 mVrFlingerRequestsDisplay = false;
1397 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001398 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001399
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401
Steven Thomasb02664d2017-07-26 18:48:28 -07001402 int currentDisplayPowerMode = getDisplayDeviceLocked(
1403 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001404
Steven Thomasb02664d2017-07-26 18:48:28 -07001405 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001408
Steven Thomasb02664d2017-07-26 18:48:28 -07001409 resetDisplayState();
1410 mHwc.reset(); // Delete the current instance before creating the new one
1411 mHwc.reset(new HWComposer(
1412 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1413 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001414
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1416 "Switched to non-remote hardware composer");
1417
1418 if (vrFlingerRequestsDisplay) {
1419 mVrFlinger->GrantDisplayOwnership();
1420 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001422 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001423
1424 mVisibleRegionsDirty = true;
1425 invalidateHwcGeometry();
1426
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001427 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001428 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1429 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1430 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001431
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 // Reset the timing values to account for the period of the swapped in HWC
1433 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1434 const nsecs_t period = activeConfig->getVsyncPeriod();
1435 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001436
Steven Thomasb02664d2017-07-26 18:48:28 -07001437 // Use phase of 0 since phase is not known.
1438 // Use latency of 0, which will snap to the ideal latency.
1439 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001440
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441 android_atomic_or(1, &mRepaintEverything);
1442 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001443}
1444
Mathias Agopian4fec8732012-06-29 14:12:52 -07001445void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001446 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001447 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001448 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001449 bool frameMissed = !mHadClientComposition &&
1450 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001451 (mPreviousPresentFence->getSignalTime() ==
1452 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001453 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001454 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001455 signalLayerUpdate();
1456 break;
1457 }
1458
Steven Thomas050b2c82017-03-06 11:45:16 -08001459 // Now that we're going to make it to the handleMessageTransaction()
1460 // call below it's safe to call updateVrFlinger(), which will
1461 // potentially trigger a display handoff.
1462 updateVrFlinger();
1463
Dan Stoza6b9454d2014-11-07 16:00:59 -08001464 bool refreshNeeded = handleMessageTransaction();
1465 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001466 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001467 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001468 // Signal a refresh if a transaction modified the window state,
1469 // a new buffer was latched, or if HWC has requested a full
1470 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001471 signalRefresh();
1472 }
1473 break;
1474 }
1475 case MessageQueue::REFRESH: {
1476 handleMessageRefresh();
1477 break;
1478 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001479 }
1480}
1481
Dan Stoza6b9454d2014-11-07 16:00:59 -08001482bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001483 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001484 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001485 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001486 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001487 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001488 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001489}
1490
Dan Stoza6b9454d2014-11-07 16:00:59 -08001491bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001492 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001493 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001494}
1495
1496void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001497 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001498
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001499 mRefreshPending = false;
1500
Pablo Ceballos40845df2016-01-25 17:41:15 -08001501 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001502
Brian Andersond6927fb2016-07-23 23:37:30 -07001503 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001504 rebuildLayerStacks();
1505 setUpHWComposer();
1506 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001507 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001508 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001509 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001510
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001511 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001512
1513 mHadClientComposition = false;
1514 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1515 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1516 mHadClientComposition = mHadClientComposition ||
1517 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1518 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001519
Dan Stoza9e56aa02015-11-02 13:00:03 -08001520 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001521}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001522
Mathias Agopiancd60f992012-08-16 16:28:27 -07001523void SurfaceFlinger::doDebugFlashRegions()
1524{
1525 // is debugging enabled
1526 if (CC_LIKELY(!mDebugRegion))
1527 return;
1528
1529 const bool repaintEverything = mRepaintEverything;
1530 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1531 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001532 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001533 // transform the dirty region into this screen's coordinate space
1534 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1535 if (!dirtyRegion.isEmpty()) {
1536 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001537 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001538
1539 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001540 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001541 RenderEngine& engine(getRenderEngine());
1542 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1543
Mathias Agopianda27af92012-09-13 18:17:13 -07001544 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545 }
1546 }
1547 }
1548
1549 postFramebuffer();
1550
1551 if (mDebugRegion > 1) {
1552 usleep(mDebugRegion * 1000);
1553 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001554
Dan Stoza9e56aa02015-11-02 13:00:03 -08001555 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001556 auto& displayDevice = mDisplays[displayId];
1557 if (!displayDevice->isDisplayOn()) {
1558 continue;
1559 }
1560
1561 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001562 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1563 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001564 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565}
1566
Adrian Roos1e1a1282017-11-01 19:05:31 +01001567void SurfaceFlinger::doTracing(const char* where) {
1568 ATRACE_CALL();
1569 ATRACE_NAME(where);
1570 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001571 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001572 }
1573}
1574
Brian Andersond6927fb2016-07-23 23:37:30 -07001575void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001576{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001577 ATRACE_CALL();
1578 ALOGV("preComposition");
1579
Mathias Agopiancd60f992012-08-16 16:28:27 -07001580 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001581 mDrawingState.traverseInZOrder([&](Layer* layer) {
1582 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001583 needExtraInvalidate = true;
1584 }
Robert Carr2047fae2016-11-28 14:09:09 -08001585 });
1586
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587 if (needExtraInvalidate) {
1588 signalLayerUpdate();
1589 }
1590}
1591
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001592void SurfaceFlinger::updateCompositorTiming(
1593 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1594 std::shared_ptr<FenceTime>& presentFenceTime) {
1595 // Update queue of past composite+present times and determine the
1596 // most recently known composite to present latency.
1597 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1598 nsecs_t compositeToPresentLatency = -1;
1599 while (!mCompositePresentTimes.empty()) {
1600 CompositePresentTime& cpt = mCompositePresentTimes.front();
1601 // Cached values should have been updated before calling this method,
1602 // which helps avoid duplicate syscalls.
1603 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1604 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1605 break;
1606 }
1607 compositeToPresentLatency = displayTime - cpt.composite;
1608 mCompositePresentTimes.pop();
1609 }
1610
1611 // Don't let mCompositePresentTimes grow unbounded, just in case.
1612 while (mCompositePresentTimes.size() > 16) {
1613 mCompositePresentTimes.pop();
1614 }
1615
Brian Andersond0010582017-03-07 13:20:31 -08001616 setCompositorTimingSnapped(
1617 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1618}
1619
1620void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1621 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001622 // Integer division and modulo round toward 0 not -inf, so we need to
1623 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001624 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001625 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1626 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1627
Brian Andersond0010582017-03-07 13:20:31 -08001628 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1629 if (idealLatency <= 0) {
1630 idealLatency = vsyncInterval;
1631 }
1632
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001633 // Snap the latency to a value that removes scheduling jitter from the
1634 // composition and present times, which often have >1ms of jitter.
1635 // Reducing jitter is important if an app attempts to extrapolate
1636 // something (such as user input) to an accurate diasplay time.
1637 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1638 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001639 nsecs_t bias = vsyncInterval / 2;
1640 int64_t extraVsyncs =
1641 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1642 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1643 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001644
Brian Andersond0010582017-03-07 13:20:31 -08001645 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001646 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1647 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001648 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001649}
1650
1651void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001652{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001653 ATRACE_CALL();
1654 ALOGV("postComposition");
1655
Brian Anderson3546a3f2016-07-14 11:51:14 -07001656 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001657 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001658 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001659 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001660 }
1661
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001662 // |mStateLock| not needed as we are on the main thread
1663 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001664
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001665 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001666 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1667 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1668 glCompositionDoneFenceTime =
1669 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1670 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1671 } else {
1672 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1673 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001674
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001675 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001676 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1677 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1678 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001679
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1681 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1682
1683 // We use the refreshStartTime which might be sampled a little later than
1684 // when we started doing work for this frame, but that should be okay
1685 // since updateCompositorTiming has snapping logic.
1686 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001687 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001688 CompositorTiming compositorTiming;
1689 {
1690 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1691 compositorTiming = mCompositorTiming;
1692 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001693
Robert Carr2047fae2016-11-28 14:09:09 -08001694 mDrawingState.traverseInZOrder([&](Layer* layer) {
1695 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001696 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001697 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001698 recordBufferingStats(layer->getName().string(),
1699 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001700 }
Robert Carr2047fae2016-11-28 14:09:09 -08001701 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001702
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001703 if (presentFenceTime->isValid()) {
1704 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001705 enableHardwareVsync();
1706 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001707 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001708 }
1709 }
1710
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001711 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001712 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001713 enableHardwareVsync();
1714 }
1715 }
1716
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001717 if (mAnimCompositionPending) {
1718 mAnimCompositionPending = false;
1719
Brian Anderson4e606e32017-03-16 15:34:57 -07001720 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001721 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001722 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001723 } else {
1724 // The HWC doesn't support present fences, so use the refresh
1725 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001726 nsecs_t presentTime =
1727 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001728 mAnimFrameTracker.setActualPresentTime(presentTime);
1729 }
1730 mAnimFrameTracker.advanceFrame();
1731 }
Dan Stozab90cf072015-03-05 11:05:59 -08001732
1733 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1734 return;
1735 }
1736
1737 nsecs_t currentTime = systemTime();
1738 if (mHasPoweredOff) {
1739 mHasPoweredOff = false;
1740 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001741 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001742 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001743 if (numPeriods < NUM_BUCKETS - 1) {
1744 mFrameBuckets[numPeriods] += elapsedTime;
1745 } else {
1746 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1747 }
1748 mTotalTime += elapsedTime;
1749 }
1750 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001751}
1752
1753void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001754 ATRACE_CALL();
1755 ALOGV("rebuildLayerStacks");
1756
Mathias Agopiancd60f992012-08-16 16:28:27 -07001757 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001758 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001759 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001760 mVisibleRegionsDirty = false;
1761 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001762
Jeff Sharkey76488112017-02-27 14:15:18 -07001763 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1764 Region opaqueRegion;
1765 Region dirtyRegion;
1766 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001767 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001768 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1769 const Transform& tr(displayDevice->getTransform());
1770 const Rect bounds(displayDevice->getBounds());
1771 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001772 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001773
Jeff Sharkey76488112017-02-27 14:15:18 -07001774 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001775 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001776 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1777 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001778 Region drawRegion(tr.transform(
1779 layer->visibleNonTransparentRegion));
1780 drawRegion.andSelf(bounds);
1781 if (!drawRegion.isEmpty()) {
1782 layersSortedByZ.add(layer);
1783 } else {
1784 // Clear out the HWC layer if this layer was
1785 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001786 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001787 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001788 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001789 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001790 // WM changes displayDevice->layerStack upon sleep/awake.
1791 // Here we make sure we delete the HWC layers even if
1792 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001793 hwcLayerDestroyed = layer->destroyHwcLayer(
1794 displayDevice->getHwcDisplayId());
1795 }
1796
1797 // If a layer is not going to get a release fence because
1798 // it is invisible, but it is also going to release its
1799 // old buffer, add it to the list of layers needing
1800 // fences.
1801 if (hwcLayerDestroyed) {
1802 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1803 mLayersWithQueuedFrames.cend(), layer);
1804 if (found != mLayersWithQueuedFrames.cend()) {
1805 layersNeedingFences.add(layer);
1806 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001807 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001808 });
1809 }
1810 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001811 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001812 displayDevice->undefinedRegion.set(bounds);
1813 displayDevice->undefinedRegion.subtractSelf(
1814 tr.transform(opaqueRegion));
1815 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001816 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001817 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001818}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001819
Romain Guy0147a172017-06-01 13:53:56 -07001820mat4 SurfaceFlinger::computeSaturationMatrix() const {
1821 if (mSaturation == 1.0f) {
1822 return mat4();
1823 }
1824
1825 // Rec.709 luma coefficients
1826 float3 luminance{0.213f, 0.715f, 0.072f};
1827 luminance *= 1.0f - mSaturation;
1828 return mat4(
1829 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1830 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1831 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1832 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1833 );
1834}
1835
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001836// pickColorMode translates a given dataspace into the best available color mode.
1837// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001838android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001839 if (mForceNativeColorMode) {
1840 return HAL_COLOR_MODE_NATIVE;
1841 }
1842
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001843 switch (dataSpace) {
1844 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1845 // system expects.
1846 case HAL_DATASPACE_UNKNOWN:
1847 case HAL_DATASPACE_SRGB:
1848 case HAL_DATASPACE_V0_SRGB:
1849 return HAL_COLOR_MODE_SRGB;
1850 break;
1851
1852 case HAL_DATASPACE_DISPLAY_P3:
1853 return HAL_COLOR_MODE_DISPLAY_P3;
1854 break;
1855
1856 default:
1857 // TODO (courtneygo): Do we want to assert an error here?
1858 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1859 dataSpace);
1860 return HAL_COLOR_MODE_SRGB;
1861 break;
1862 }
1863}
1864
Romain Guy0147a172017-06-01 13:53:56 -07001865android_dataspace SurfaceFlinger::bestTargetDataSpace(
1866 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001867 // Only support sRGB and Display-P3 right now.
1868 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1869 return HAL_DATASPACE_DISPLAY_P3;
1870 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001871 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1872 return HAL_DATASPACE_DISPLAY_P3;
1873 }
1874 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1875 return HAL_DATASPACE_DISPLAY_P3;
1876 }
1877
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001878 return HAL_DATASPACE_V0_SRGB;
1879}
1880
Mathias Agopiancd60f992012-08-16 16:28:27 -07001881void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001882 ATRACE_CALL();
1883 ALOGV("setUpHWComposer");
1884
Jesse Hall028dc8f2013-08-20 16:35:32 -07001885 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001886 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1887 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1888 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1889
1890 // If nothing has changed (!dirty), don't recompose.
1891 // If something changed, but we don't currently have any visible layers,
1892 // and didn't when we last did a composition, then skip it this time.
1893 // The second rule does two things:
1894 // - When all layers are removed from a display, we'll emit one black
1895 // frame, then nothing more until we get new layers.
1896 // - When a display is created with a private layer stack, we won't
1897 // emit any black frames until a layer is added to the layer stack.
1898 bool mustRecompose = dirty && !(empty && wasEmpty);
1899
1900 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1901 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1902 mustRecompose ? "doing" : "skipping",
1903 dirty ? "+" : "-",
1904 empty ? "+" : "-",
1905 wasEmpty ? "+" : "-");
1906
Dan Stoza71433162014-02-04 16:22:36 -08001907 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001908
1909 if (mustRecompose) {
1910 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1911 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001912 }
1913
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 // build the h/w work list
1915 if (CC_UNLIKELY(mGeometryInvalid)) {
1916 mGeometryInvalid = false;
1917 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1918 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1919 const auto hwcId = displayDevice->getHwcDisplayId();
1920 if (hwcId >= 0) {
1921 const Vector<sp<Layer>>& currentLayers(
1922 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001923 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001924 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001926 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001927 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001928 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001929 }
1930 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001931
Robert Carrae060832016-11-28 10:51:00 -08001932 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001933 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001935 }
1936 }
1937 }
1938 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939 }
Riley Andrews03414a12014-07-01 14:22:59 -07001940
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001941
Romain Guy0147a172017-06-01 13:53:56 -07001942 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001943
Dan Stoza9e56aa02015-11-02 13:00:03 -08001944 // Set the per-frame data
1945 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1946 auto& displayDevice = mDisplays[displayId];
1947 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001948
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 if (hwcId < 0) {
1950 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001951 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001952 if (colorMatrix != mPreviousColorMatrix) {
1953 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1954 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1955 "display %zd: %d", displayId, result);
1956 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
chaviwc9232ed2017-11-14 15:31:15 -08001958 if (layer->getForceClientComposition(hwcId)) {
1959 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1960 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1961 continue;
1962 }
1963
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964 layer->setPerFrameData(displayDevice);
1965 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001966
1967 if (hasWideColorDisplay) {
1968 android_color_mode newColorMode;
1969 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1970
1971 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1972 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1973 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1974 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1975 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1976 }
1977 newColorMode = pickColorMode(newDataSpace);
1978
Thierry Strudel2924d012017-08-14 15:19:37 -07001979 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001980 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001981 }
1982
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001983 mPreviousColorMatrix = colorMatrix;
1984
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001986 auto& displayDevice = mDisplays[displayId];
1987 if (!displayDevice->isDisplayOn()) {
1988 continue;
1989 }
1990
1991 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1993 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001994 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001995}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001996
Mathias Agopiancd60f992012-08-16 16:28:27 -07001997void SurfaceFlinger::doComposition() {
1998 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001999 ALOGV("doComposition");
2000
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002001 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002002 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002003 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002004 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002005 // transform the dirty region into this screen's coordinate space
2006 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002007
2008 // repaint the framebuffer (if needed)
2009 doDisplayComposition(hw, dirtyRegion);
2010
Mathias Agopiancd60f992012-08-16 16:28:27 -07002011 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002012 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002013 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002014 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002015 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002016}
2017
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002018void SurfaceFlinger::postFramebuffer()
2019{
Mathias Agopian841cde52012-03-01 15:44:37 -08002020 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002021 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002022
Mathias Agopiana44b0412011-10-16 18:46:35 -07002023 const nsecs_t now = systemTime();
2024 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002025
Dan Stoza9e56aa02015-11-02 13:00:03 -08002026 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2027 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002028 if (!displayDevice->isDisplayOn()) {
2029 continue;
2030 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002031 const auto hwcId = displayDevice->getHwcDisplayId();
2032 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002033 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002034 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002035 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002036 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002037 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002038 // The layer buffer from the previous frame (if any) is released
2039 // by HWC only when the release fence from this frame (if any) is
2040 // signaled. Always get the release fence from HWC first.
2041 auto hwcLayer = layer->getHwcLayer(hwcId);
2042 sp<Fence> releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2043
2044 // If the layer was client composited in the previous frame, we
2045 // need to merge with the previous client target acquire fence.
2046 // Since we do not track that, always merge with the current
2047 // client target acquire fence when it is available, even though
2048 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002049 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002050 releaseFence = Fence::merge("LayerRelease", releaseFence,
2051 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002052 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002053
Dan Stoza9e56aa02015-11-02 13:00:03 -08002054 layer->onLayerDisplayed(releaseFence);
2055 }
Chia-I Wu83806892017-11-16 10:50:20 -08002056
2057 // We've got a list of layers needing fences, that are disjoint with
2058 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2059 // supply them with the present fence.
2060 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
2061 sp<Fence> presentFence = mHwc->getPresentFence(hwcId);
2062 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2063 layer->onLayerDisplayed(presentFence);
2064 }
2065 }
2066
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 if (hwcId >= 0) {
2068 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002069 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002070 }
2071
Mathias Agopiana44b0412011-10-16 18:46:35 -07002072 mLastSwapBufferTime = systemTime() - now;
2073 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002074
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002075 // |mStateLock| not needed as we are on the main thread
2076 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002077 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2078 logFrameStats();
2079 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002080}
2081
Mathias Agopian87baae12012-07-31 12:38:26 -07002082void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002083{
Mathias Agopian841cde52012-03-01 15:44:37 -08002084 ATRACE_CALL();
2085
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002086 // here we keep a copy of the drawing state (that is the state that's
2087 // going to be overwritten by handleTransactionLocked()) outside of
2088 // mStateLock so that the side-effects of the State assignment
2089 // don't happen with mStateLock held (which can cause deadlocks).
2090 State drawingState(mDrawingState);
2091
Mathias Agopianca4d3602011-05-19 15:38:14 -07002092 Mutex::Autolock _l(mStateLock);
2093 const nsecs_t now = systemTime();
2094 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002095
Mathias Agopianca4d3602011-05-19 15:38:14 -07002096 // Here we're guaranteed that some transaction flags are set
2097 // so we can call handleTransactionLocked() unconditionally.
2098 // We call getTransactionFlags(), which will also clear the flags,
2099 // with mStateLock held to guarantee that mCurrentState won't change
2100 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002101
Mathias Agopiane57f2922012-08-09 16:29:12 -07002102 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002103 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002104
Mathias Agopianca4d3602011-05-19 15:38:14 -07002105 mLastTransactionTime = systemTime() - now;
2106 mDebugInTransaction = 0;
2107 invalidateHwcGeometry();
2108 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002109}
2110
Mathias Agopian87baae12012-07-31 12:38:26 -07002111void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002112{
Dan Stoza7dde5992015-05-22 09:51:44 -07002113 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002114 mCurrentState.traverseInZOrder([](Layer* layer) {
2115 layer->notifyAvailableFrames();
2116 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002118 /*
2119 * Traversal of the children
2120 * (perform the transaction for each of them if needed)
2121 */
2122
Mathias Agopian3559b072012-08-15 13:46:03 -07002123 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002124 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002125 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002126 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002127
2128 const uint32_t flags = layer->doTransaction(0);
2129 if (flags & Layer::eVisibleRegion)
2130 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002131 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002132 }
2133
2134 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002135 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002136 */
2137
Mathias Agopiane57f2922012-08-09 16:29:12 -07002138 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002139 // here we take advantage of Vector's copy-on-write semantics to
2140 // improve performance by skipping the transaction entirely when
2141 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002142 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2143 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002144 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002145 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002146 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002147 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002148
2149 // find the displays that were removed
2150 // (ie: in drawing state but not in current state)
2151 // also handle displays that changed
2152 // (ie: displays that are in both lists)
Ivan Lozano51a0b412017-12-06 17:07:27 -08002153 for (size_t i=0 ; i<dc ;) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002154 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2155 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002156 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002157 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002158 // Call makeCurrent() on the primary display so we can
2159 // be sure that nothing associated with this display
2160 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002161 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Chia-I Wu7f402902017-11-09 12:51:10 -08002162 defaultDisplay->makeCurrent();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002163 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002164 if (hw != NULL)
2165 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002166 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002167 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002168 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002169 } else {
2170 ALOGW("trying to remove the main display");
2171 }
2172 } else {
2173 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002174 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002175 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002176 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2177 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002178 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002179 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002180 // recreating the DisplayDevice, so we just remove it
2181 // from the drawing state, so that it get re-added
2182 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002183 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002184 if (hw != NULL)
2185 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002186 mDisplays.removeItem(display);
2187 mDrawingState.displays.removeItemsAt(i);
Ivan Lozano51a0b412017-12-06 17:07:27 -08002188 dc--;
Mathias Agopian93997a82012-08-29 17:30:36 -07002189 // at this point we must loop to the next item
2190 continue;
2191 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002192
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002193 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002194 if (disp != NULL) {
2195 if (state.layerStack != draw[i].layerStack) {
2196 disp->setLayerStack(state.layerStack);
2197 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002198 if ((state.orientation != draw[i].orientation)
2199 || (state.viewport != draw[i].viewport)
2200 || (state.frame != draw[i].frame))
2201 {
2202 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002203 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002204 }
Michael Lentine47e45402014-07-18 15:34:25 -07002205 if (state.width != draw[i].width || state.height != draw[i].height) {
2206 disp->setDisplaySize(state.width, state.height);
2207 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002208 }
2209 }
Ivan Lozano51a0b412017-12-06 17:07:27 -08002210 ++i;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002211 }
2212
2213 // find displays that were added
2214 // (ie: in current state but not in drawing state)
2215 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002216 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002217 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002218
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002219 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002220 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002221 sp<IGraphicBufferProducer> bqProducer;
2222 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002223 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002224
Dan Stoza9e56aa02015-11-02 13:00:03 -08002225 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002226 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002227 // Virtual displays without a surface are dormant:
2228 // they have external state (layer stack, projection,
2229 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002230 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002231
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002232 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002233 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002234 int width = 0;
2235 int status = state.surface->query(
2236 NATIVE_WINDOW_WIDTH, &width);
2237 ALOGE_IF(status != NO_ERROR,
2238 "Unable to query width (%d)", status);
2239 int height = 0;
2240 status = state.surface->query(
2241 NATIVE_WINDOW_HEIGHT, &height);
2242 ALOGE_IF(status != NO_ERROR,
2243 "Unable to query height (%d)", status);
2244 int intFormat = 0;
2245 status = state.surface->query(
2246 NATIVE_WINDOW_FORMAT, &intFormat);
2247 ALOGE_IF(status != NO_ERROR,
2248 "Unable to query format (%d)", status);
2249 auto format = static_cast<android_pixel_format_t>(
2250 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002251
Dan Stoza8cf150a2016-08-02 10:27:31 -07002252 mHwc->allocateVirtualDisplay(width, height, &format,
2253 &hwcId);
2254 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002255
Dan Stoza5cf424b2016-05-20 14:02:39 -07002256 // TODO: Plumb requested format back up to consumer
2257
Dan Stoza9e56aa02015-11-02 13:00:03 -08002258 sp<VirtualDisplaySurface> vds =
2259 new VirtualDisplaySurface(*mHwc,
2260 hwcId, state.surface, bqProducer,
2261 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002262
2263 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002264 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002265 }
2266 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002267 ALOGE_IF(state.surface!=NULL,
2268 "adding a supported display, but rendering "
2269 "surface is provided (%p), ignoring it",
2270 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002271
2272 hwcId = state.type;
2273 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2274 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002275 }
2276
2277 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002278 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002279 sp<DisplayDevice> hw =
2280 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wuc670d502017-11-09 23:17:51 -08002281 dispSurface, producer, hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002282 hw->setLayerStack(state.layerStack);
2283 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002284 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002285 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002286 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002287 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002288 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002289 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002290 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002291 }
2292 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002293 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002294 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002295
Mathias Agopian84300952012-11-21 16:02:13 -08002296 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2297 // The transform hint might have changed for some layers
2298 // (either because a display has changed, or because a layer
2299 // as changed).
2300 //
2301 // Walk through all the layers in currentLayers,
2302 // and update their transform hint.
2303 //
2304 // If a layer is visible only on a single display, then that
2305 // display is used to calculate the hint, otherwise we use the
2306 // default display.
2307 //
2308 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2309 // the hint is set before we acquire a buffer from the surface texture.
2310 //
2311 // NOTE: layer transactions have taken place already, so we use their
2312 // drawing state. However, SurfaceFlinger's own transaction has not
2313 // happened yet, so we must use the current state layer list
2314 // (soon to become the drawing state list).
2315 //
2316 sp<const DisplayDevice> disp;
2317 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002318 bool first = true;
2319 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002320 // NOTE: we rely on the fact that layers are sorted by
2321 // layerStack first (so we don't have to traverse the list
2322 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002323 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002324 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002325 currentlayerStack = layerStack;
2326 // figure out if this layerstack is mirrored
2327 // (more than one display) if so, pick the default display,
2328 // if not, pick the only display it's on.
2329 disp.clear();
2330 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2331 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002332 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002333 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002334 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002335 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002336 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002337 break;
2338 }
2339 }
2340 }
2341 }
Chet Haase91d25932013-04-11 15:24:55 -07002342 if (disp == NULL) {
2343 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2344 // redraw after transform hint changes. See bug 8508397.
2345
2346 // could be null when this layer is using a layerStack
2347 // that is not visible on any display. Also can occur at
2348 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002349 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002350 }
Chet Haase91d25932013-04-11 15:24:55 -07002351 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002352
2353 first = false;
2354 });
Mathias Agopian84300952012-11-21 16:02:13 -08002355 }
2356
2357
Mathias Agopian3559b072012-08-15 13:46:03 -07002358 /*
2359 * Perform our own transaction if needed
2360 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002361
2362 if (mLayersAdded) {
2363 mLayersAdded = false;
2364 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002365 mVisibleRegionsDirty = true;
2366 }
2367
2368 // some layers might have been removed, so
2369 // we need to update the regions they're exposing.
2370 if (mLayersRemoved) {
2371 mLayersRemoved = false;
2372 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002373 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002374 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002375 // this layer is not visible anymore
2376 // TODO: we could traverse the tree from front to back and
2377 // compute the actual visible region
2378 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002379 Region visibleReg;
2380 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002381 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002382 }
Robert Carr2047fae2016-11-28 14:09:09 -08002383 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384 }
2385
2386 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002387
2388 updateCursorAsync();
2389}
2390
2391void SurfaceFlinger::updateCursorAsync()
2392{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002393 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2394 auto& displayDevice = mDisplays[displayId];
2395 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002396 continue;
2397 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002398
2399 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2400 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002401 }
2402 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002403}
2404
2405void SurfaceFlinger::commitTransaction()
2406{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002407 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002408 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002409 for (const auto& l : mLayersPendingRemoval) {
2410 recordBufferingStats(l->getName().string(),
2411 l->getOccupancyHistory(true));
2412 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002413 }
2414 mLayersPendingRemoval.clear();
2415 }
2416
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002417 // If this transaction is part of a window animation then the next frame
2418 // we composite should be considered an animation as well.
2419 mAnimCompositionPending = mAnimTransactionPending;
2420
Mathias Agopian4fec8732012-06-29 14:12:52 -07002421 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002422 mDrawingState.traverseInZOrder([](Layer* layer) {
2423 layer->commitChildList();
2424 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002425 mTransactionPending = false;
2426 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002427 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002428}
2429
Chia-I Wuab0c3192017-08-01 11:29:00 -07002430void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002431 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002432{
Mathias Agopian841cde52012-03-01 15:44:37 -08002433 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002434 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002435
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002436 Region aboveOpaqueLayers;
2437 Region aboveCoveredLayers;
2438 Region dirty;
2439
Mathias Agopian87baae12012-07-31 12:38:26 -07002440 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002441
Robert Carr2047fae2016-11-28 14:09:09 -08002442 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002443 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002444 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445
Jesse Hall01e29052013-02-19 16:13:35 -08002446 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002447 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002448 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002449
Mathias Agopianab028732010-03-16 16:41:46 -07002450 /*
2451 * opaqueRegion: area of a surface that is fully opaque.
2452 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002453 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002454
2455 /*
2456 * visibleRegion: area of a surface that is visible on screen
2457 * and not fully transparent. This is essentially the layer's
2458 * footprint minus the opaque regions above it.
2459 * Areas covered by a translucent surface are considered visible.
2460 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002461 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002462
2463 /*
2464 * coveredRegion: area of a surface that is covered by all
2465 * visible regions above it (which includes the translucent areas).
2466 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002468
Jesse Halla8026d22012-09-25 13:25:04 -07002469 /*
2470 * transparentRegion: area of a surface that is hinted to be completely
2471 * transparent. This is only used to tell when the layer has no visible
2472 * non-transparent regions and can be removed from the layer list. It
2473 * does not affect the visibleRegion of this layer or any layers
2474 * beneath it. The hint may not be correct if apps don't respect the
2475 * SurfaceView restrictions (which, sadly, some don't).
2476 */
2477 Region transparentRegion;
2478
Mathias Agopianab028732010-03-16 16:41:46 -07002479
2480 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002481 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002482 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002483 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002485 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002486 if (!visibleRegion.isEmpty()) {
2487 // Remove the transparent area from the visible region
2488 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002489 if (tr.preserveRects()) {
2490 // transform the transparent region
2491 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002492 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002493 // transformation too complex, can't do the
2494 // transparent region optimization.
2495 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002496 }
Mathias Agopianab028732010-03-16 16:41:46 -07002497 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498
Mathias Agopianab028732010-03-16 16:41:46 -07002499 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002500 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002501 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002502 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2503 // the opaque region is the layer's footprint
2504 opaqueRegion = visibleRegion;
2505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506 }
2507 }
2508
Mathias Agopianab028732010-03-16 16:41:46 -07002509 // Clip the covered region to the visible region
2510 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2511
2512 // Update aboveCoveredLayers for next (lower) layer
2513 aboveCoveredLayers.orSelf(visibleRegion);
2514
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515 // subtract the opaque region covered by the layers above us
2516 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517
2518 // compute this layer's dirty region
2519 if (layer->contentDirty) {
2520 // we need to invalidate the whole region
2521 dirty = visibleRegion;
2522 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002523 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524 layer->contentDirty = false;
2525 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002526 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002527 * the exposed region consists of two components:
2528 * 1) what's VISIBLE now and was COVERED before
2529 * 2) what's EXPOSED now less what was EXPOSED before
2530 *
2531 * note that (1) is conservative, we start with the whole
2532 * visible region but only keep what used to be covered by
2533 * something -- which mean it may have been exposed.
2534 *
2535 * (2) handles areas that were not covered by anything but got
2536 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002537 */
Mathias Agopianab028732010-03-16 16:41:46 -07002538 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002539 const Region oldVisibleRegion = layer->visibleRegion;
2540 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002541 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2542 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543 }
2544 dirty.subtractSelf(aboveOpaqueLayers);
2545
2546 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002547 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002548
Mathias Agopianab028732010-03-16 16:41:46 -07002549 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002550 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002551
Jesse Halla8026d22012-09-25 13:25:04 -07002552 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002553 layer->setVisibleRegion(visibleRegion);
2554 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002555 layer->setVisibleNonTransparentRegion(
2556 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002557 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558
Mathias Agopian87baae12012-07-31 12:38:26 -07002559 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002560}
2561
Chia-I Wuab0c3192017-08-01 11:29:00 -07002562void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002563 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002564 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002565 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002566 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002567 }
2568 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002569}
2570
Dan Stoza6b9454d2014-11-07 16:00:59 -08002571bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002573 ALOGV("handlePageFlip");
2574
Brian Andersond6927fb2016-07-23 23:37:30 -07002575 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576
Mathias Agopian4fec8732012-06-29 14:12:52 -07002577 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002578 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002579 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002580
2581 // Store the set of layers that need updates. This set must not change as
2582 // buffers are being latched, as this could result in a deadlock.
2583 // Example: Two producers share the same command stream and:
2584 // 1.) Layer 0 is latched
2585 // 2.) Layer 0 gets a new frame
2586 // 2.) Layer 1 gets a new frame
2587 // 3.) Layer 1 is latched.
2588 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2589 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002590 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002591 if (layer->hasQueuedFrame()) {
2592 frameQueued = true;
2593 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002594 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002595 } else {
2596 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002597 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002598 } else {
2599 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002600 }
Robert Carr2047fae2016-11-28 14:09:09 -08002601 });
2602
Dan Stoza9e56aa02015-11-02 13:00:03 -08002603 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002604 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002605 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002606 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002607 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002608 newDataLatched = true;
2609 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002610 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002611
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002612 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002613
2614 // If we will need to wake up at some time in the future to deal with a
2615 // queued frame that shouldn't be displayed during this vsync period, wake
2616 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002617 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002618 signalLayerUpdate();
2619 }
2620
2621 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002622 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002623}
2624
Mathias Agopianad456f92011-01-13 17:53:01 -08002625void SurfaceFlinger::invalidateHwcGeometry()
2626{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002627 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002628}
2629
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002630
Fabien Sanglard830b8472016-11-30 16:35:58 -08002631void SurfaceFlinger::doDisplayComposition(
2632 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002633 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634{
Dan Stoza71433162014-02-04 16:22:36 -08002635 // We only need to actually compose the display if:
2636 // 1) It is being handled by hardware composer, which may need this to
2637 // keep its virtual display state machine in sync, or
2638 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002639 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002640 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002641 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002642 return;
2643 }
2644
Dan Stoza9e56aa02015-11-02 13:00:03 -08002645 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002646 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002647
2648 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002649 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650}
2651
Chia-I Wub02087d2017-11-09 10:19:54 -08002652bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002653{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002654 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002655
Chia-I Wub02087d2017-11-09 10:19:54 -08002656 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002657 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002658 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002659
2660 mat4 oldColorMatrix;
2661 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2662 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2663 if (applyColorMatrix) {
2664 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2665 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2666 }
2667
Dan Stoza9e56aa02015-11-02 13:00:03 -08002668 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2669 if (hasClientComposition) {
2670 ALOGV("hasClientComposition");
2671
Romain Guy54f154a2017-10-24 21:40:32 +01002672 mRenderEngine->setWideColor(
2673 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2674 mRenderEngine->setColorMode(mForceNativeColorMode ?
2675 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Chia-I Wu7f402902017-11-09 12:51:10 -08002676 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002677 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002678 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002679 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002680
2681 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002682 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002683 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2684 }
2685 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002686 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002687
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002688 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002689 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2690 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002691 // when using overlays, we assume a fully transparent framebuffer
2692 // NOTE: we could reduce how much we need to clear, for instance
2693 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002694 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002695 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002696 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002697 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002698 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002699 // we're left with the letterbox region
2700 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002701 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002702
2703 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002704 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002705
Mathias Agopianb9494d52012-04-18 02:28:45 -07002706 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002707 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002708 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002709 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002710 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002711 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002712
Dan Stoza9e56aa02015-11-02 13:00:03 -08002713 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002714 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002715 // scissor on the main display. It should never be needed
2716 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002717 const Rect& bounds(displayDevice->getBounds());
2718 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002719 if (scissor != bounds) {
2720 // scissor doesn't match the screen's dimensions, so we
2721 // need to clear everything outside of it and enable
2722 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002723
Mathias Agopianf45c5102012-10-24 16:29:17 -07002724 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002725 const uint32_t height = displayDevice->getHeight();
2726 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002727 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002728 }
2729 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002730 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002731
Mathias Agopian85d751c2012-08-29 16:59:24 -07002732 /*
2733 * and then, render the layers targeted at the framebuffer
2734 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002735
Dan Stoza9e56aa02015-11-02 13:00:03 -08002736 ALOGV("Rendering client layers");
2737 const Transform& displayTransform = displayDevice->getTransform();
2738 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002739 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 bool firstLayer = true;
2741 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002742 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002743 displayTransform.transform(layer->visibleRegion)));
2744 ALOGV("Layer: %s", layer->getName().string());
2745 ALOGV(" Composition type: %s",
2746 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002747 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002748 switch (layer->getCompositionType(hwcId)) {
2749 case HWC2::Composition::Cursor:
2750 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002751 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002753 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002754 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002755 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002756 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002757 // never clear the very first layer since we're
2758 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002759 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002760 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002761 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002762 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002763 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002764 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002765 break;
2766 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002767 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002768 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002769 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002770 } else {
2771 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002772 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002773 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002774 }
2775 } else {
2776 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002777 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002778 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002779 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002780 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002781 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002782 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002783 }
2784 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002785
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002786 if (applyColorMatrix) {
2787 getRenderEngine().setupColorTransform(oldColorMatrix);
2788 }
2789
Mathias Agopianf45c5102012-10-24 16:29:17 -07002790 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002791 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002792 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793}
2794
Fabien Sanglard830b8472016-11-30 16:35:58 -08002795void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2796 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002797 RenderEngine& engine(getRenderEngine());
2798 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799}
2800
Dan Stoza7d89d062015-04-30 13:29:25 -07002801status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002802 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002803 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002804 const sp<Layer>& lbc,
2805 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002806{
Dan Stoza7d89d062015-04-30 13:29:25 -07002807 // add this layer to the current state list
2808 {
2809 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002810 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002811 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2812 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002813 return NO_MEMORY;
2814 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002815 if (parent == nullptr) {
2816 mCurrentState.layersSortedByZ.add(lbc);
2817 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002818 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002819 ALOGE("addClientLayer called with a removed parent");
2820 return NAME_NOT_FOUND;
2821 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002822 parent->addChild(lbc);
2823 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002824
Dan Stoza7d89d062015-04-30 13:29:25 -07002825 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002826 mLayersAdded = true;
2827 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002828 }
2829
Mathias Agopian96f08192010-06-02 23:28:45 -07002830 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002831 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002832
Dan Stoza7d89d062015-04-30 13:29:25 -07002833 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002834}
2835
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002836status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002837 Mutex::Autolock _l(mStateLock);
2838
chaviw8b3871a2017-11-01 17:41:01 -07002839 if (layer->isPendingRemoval()) {
2840 return NO_ERROR;
2841 }
2842
Robert Carr1f0a16a2016-10-24 16:27:39 -07002843 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002844 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002845 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002846 if (topLevelOnly) {
2847 return NO_ERROR;
2848 }
2849
Chia-I Wu98f1c102017-05-30 14:54:08 -07002850 sp<Layer> ancestor = p;
2851 while (ancestor->getParent() != nullptr) {
2852 ancestor = ancestor->getParent();
2853 }
2854 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2855 ALOGE("removeLayer called with a layer whose parent has been removed");
2856 return NAME_NOT_FOUND;
2857 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002858
2859 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002860 } else {
2861 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002862 }
2863
Robert Carr136e2f62017-02-08 17:54:29 -08002864 // As a matter of normal operation, the LayerCleaner will produce a second
2865 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2866 // so we will succeed in promoting it, but it's already been removed
2867 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2868 // otherwise something has gone wrong and we are leaking the layer.
2869 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002870 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2871 layer->getName().string(),
2872 (p != nullptr) ? p->getName().string() : "no-parent");
2873 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002874 } else if (index < 0) {
2875 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002876 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002877
Chia-I Wuc6657022017-08-15 11:18:17 -07002878 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002879 mLayersPendingRemoval.add(layer);
2880 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002881 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002882 setTransactionFlags(eTransactionNeeded);
2883 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884}
2885
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002886uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002887 return android_atomic_release_load(&mTransactionFlags);
2888}
2889
Mathias Agopian3f844832013-08-07 21:24:32 -07002890uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2892}
2893
Mathias Agopian3f844832013-08-07 21:24:32 -07002894uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2896 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002897 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898 }
2899 return old;
2900}
2901
Mathias Agopian8b33f032012-07-24 20:43:54 -07002902void SurfaceFlinger::setTransactionState(
2903 const Vector<ComposerState>& state,
2904 const Vector<DisplayState>& displays,
2905 uint32_t flags)
2906{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002907 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002908 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002909 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002910
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002911 if (flags & eAnimation) {
2912 // For window updates that are part of an animation we must wait for
2913 // previous animation "frames" to be handled.
2914 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002915 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002916 if (CC_UNLIKELY(err != NO_ERROR)) {
2917 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002918 // caller after a few seconds.
2919 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2920 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002921 mAnimTransactionPending = false;
2922 break;
2923 }
2924 }
2925 }
2926
Mathias Agopiane57f2922012-08-09 16:29:12 -07002927 size_t count = displays.size();
2928 for (size_t i=0 ; i<count ; i++) {
2929 const DisplayState& s(displays[i]);
2930 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002931 }
2932
Mathias Agopiane57f2922012-08-09 16:29:12 -07002933 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002934 for (size_t i=0 ; i<count ; i++) {
2935 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002936 // Here we need to check that the interface we're given is indeed
2937 // one of our own. A malicious client could give us a NULL
2938 // IInterface, or one of its own or even one of our own but a
2939 // different type. All these situations would cause us to crash.
2940 //
2941 // NOTE: it would be better to use RTTI as we could directly check
2942 // that we have a Client*. however, RTTI is disabled in Android.
2943 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002944 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002945 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002946 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002947 sp<Client> client( static_cast<Client *>(s.client.get()) );
2948 transactionFlags |= setClientStateLocked(client, s.state);
2949 }
2950 }
2951 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002952 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002953
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002954 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2955 // anyway. This can be used as a flush mechanism for previous async transactions.
2956 // Empty animation transaction can be used to simulate back-pressure, so also force a
2957 // transaction for empty animation transactions.
2958 if (transactionFlags == 0 &&
2959 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002960 transactionFlags = eTransactionNeeded;
2961 }
2962
Mathias Agopian386aa982011-11-07 21:58:03 -08002963 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002964 if (mInterceptor.isEnabled()) {
2965 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2966 }
Irvel468051e2016-06-13 16:44:44 -07002967
Mathias Agopian386aa982011-11-07 21:58:03 -08002968 // this triggers the transaction
2969 setTransactionFlags(transactionFlags);
2970
2971 // if this is a synchronous transaction, wait for it to take effect
2972 // before returning.
2973 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002974 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002975 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002976 if (flags & eAnimation) {
2977 mAnimTransactionPending = true;
2978 }
2979 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002980 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2981 if (CC_UNLIKELY(err != NO_ERROR)) {
2982 // just in case something goes wrong in SF, return to the
2983 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002984 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2985 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002986 break;
2987 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002988 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989 }
2990}
2991
Mathias Agopiane57f2922012-08-09 16:29:12 -07002992uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2993{
Jesse Hall9a143922012-10-04 16:29:19 -07002994 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2995 if (dpyIdx < 0)
2996 return 0;
2997
Mathias Agopiane57f2922012-08-09 16:29:12 -07002998 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002999 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003000 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003001 const uint32_t what = s.what;
3002 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003003 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003004 disp.surface = s.surface;
3005 flags |= eDisplayTransactionNeeded;
3006 }
3007 }
3008 if (what & DisplayState::eLayerStackChanged) {
3009 if (disp.layerStack != s.layerStack) {
3010 disp.layerStack = s.layerStack;
3011 flags |= eDisplayTransactionNeeded;
3012 }
3013 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003014 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003015 if (disp.orientation != s.orientation) {
3016 disp.orientation = s.orientation;
3017 flags |= eDisplayTransactionNeeded;
3018 }
3019 if (disp.frame != s.frame) {
3020 disp.frame = s.frame;
3021 flags |= eDisplayTransactionNeeded;
3022 }
3023 if (disp.viewport != s.viewport) {
3024 disp.viewport = s.viewport;
3025 flags |= eDisplayTransactionNeeded;
3026 }
3027 }
Michael Lentine47e45402014-07-18 15:34:25 -07003028 if (what & DisplayState::eDisplaySizeChanged) {
3029 if (disp.width != s.width) {
3030 disp.width = s.width;
3031 flags |= eDisplayTransactionNeeded;
3032 }
3033 if (disp.height != s.height) {
3034 disp.height = s.height;
3035 flags |= eDisplayTransactionNeeded;
3036 }
3037 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003038 }
3039 return flags;
3040}
3041
3042uint32_t SurfaceFlinger::setClientStateLocked(
3043 const sp<Client>& client,
3044 const layer_state_t& s)
3045{
Mathias Agopian13127d82013-03-05 17:47:11 -08003046 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003047 if (layer == nullptr) {
3048 return 0;
3049 }
3050
3051 if (layer->isPendingRemoval()) {
3052 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3053 return 0;
3054 }
3055
3056 uint32_t flags = 0;
3057
3058 const uint32_t what = s.what;
3059 bool geometryAppliesWithResize =
3060 what & layer_state_t::eGeometryAppliesWithResize;
3061 if (what & layer_state_t::ePositionChanged) {
3062 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3063 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003064 }
chaviw8b3871a2017-11-01 17:41:01 -07003065 }
3066 if (what & layer_state_t::eLayerChanged) {
3067 // NOTE: index needs to be calculated before we update the state
3068 const auto& p = layer->getParent();
3069 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003070 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003071 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003072 mCurrentState.layersSortedByZ.removeAt(idx);
3073 mCurrentState.layersSortedByZ.add(layer);
3074 // we need traversal (state changed)
3075 // AND transaction (list changed)
3076 flags |= eTransactionNeeded|eTraversalNeeded;
3077 }
chaviw8b3871a2017-11-01 17:41:01 -07003078 } else {
3079 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003080 flags |= eTransactionNeeded|eTraversalNeeded;
3081 }
3082 }
chaviw8b3871a2017-11-01 17:41:01 -07003083 }
3084 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003085 // NOTE: index needs to be calculated before we update the state
3086 const auto& p = layer->getParent();
3087 if (p == nullptr) {
3088 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3089 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3090 mCurrentState.layersSortedByZ.removeAt(idx);
3091 mCurrentState.layersSortedByZ.add(layer);
3092 // we need traversal (state changed)
3093 // AND transaction (list changed)
3094 flags |= eTransactionNeeded|eTraversalNeeded;
3095 }
3096 } else {
3097 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3098 flags |= eTransactionNeeded|eTraversalNeeded;
3099 }
chaviw8b3871a2017-11-01 17:41:01 -07003100 }
3101 }
3102 if (what & layer_state_t::eSizeChanged) {
3103 if (layer->setSize(s.w, s.h)) {
3104 flags |= eTraversalNeeded;
3105 }
3106 }
3107 if (what & layer_state_t::eAlphaChanged) {
3108 if (layer->setAlpha(s.alpha))
3109 flags |= eTraversalNeeded;
3110 }
3111 if (what & layer_state_t::eColorChanged) {
3112 if (layer->setColor(s.color))
3113 flags |= eTraversalNeeded;
3114 }
3115 if (what & layer_state_t::eMatrixChanged) {
3116 if (layer->setMatrix(s.matrix))
3117 flags |= eTraversalNeeded;
3118 }
3119 if (what & layer_state_t::eTransparentRegionChanged) {
3120 if (layer->setTransparentRegionHint(s.transparentRegion))
3121 flags |= eTraversalNeeded;
3122 }
3123 if (what & layer_state_t::eFlagsChanged) {
3124 if (layer->setFlags(s.flags, s.mask))
3125 flags |= eTraversalNeeded;
3126 }
3127 if (what & layer_state_t::eCropChanged) {
3128 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3129 flags |= eTraversalNeeded;
3130 }
3131 if (what & layer_state_t::eFinalCropChanged) {
3132 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3133 flags |= eTraversalNeeded;
3134 }
3135 if (what & layer_state_t::eLayerStackChanged) {
3136 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3137 // We only allow setting layer stacks for top level layers,
3138 // everything else inherits layer stack from its parent.
3139 if (layer->hasParent()) {
3140 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3141 layer->getName().string());
3142 } else if (idx < 0) {
3143 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3144 "that also does not appear in the top level layer list. Something"
3145 " has gone wrong.", layer->getName().string());
3146 } else if (layer->setLayerStack(s.layerStack)) {
3147 mCurrentState.layersSortedByZ.removeAt(idx);
3148 mCurrentState.layersSortedByZ.add(layer);
3149 // we need traversal (state changed)
3150 // AND transaction (list changed)
3151 flags |= eTransactionNeeded|eTraversalNeeded;
3152 }
3153 }
3154 if (what & layer_state_t::eDeferTransaction) {
3155 if (s.barrierHandle != nullptr) {
3156 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3157 } else if (s.barrierGbp != nullptr) {
3158 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3159 if (authenticateSurfaceTextureLocked(gbp)) {
3160 const auto& otherLayer =
3161 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3162 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3163 } else {
3164 ALOGE("Attempt to defer transaction to to an"
3165 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003166 }
3167 }
chaviw8b3871a2017-11-01 17:41:01 -07003168 // We don't trigger a traversal here because if no other state is
3169 // changed, we don't want this to cause any more work
3170 }
3171 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003172 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003173 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003174 if (!hadParent) {
3175 mCurrentState.layersSortedByZ.remove(layer);
3176 }
chaviw8b3871a2017-11-01 17:41:01 -07003177 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003178 }
chaviw8b3871a2017-11-01 17:41:01 -07003179 }
3180 if (what & layer_state_t::eReparentChildren) {
3181 if (layer->reparentChildren(s.reparentHandle)) {
3182 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003183 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003184 }
chaviw8b3871a2017-11-01 17:41:01 -07003185 if (what & layer_state_t::eDetachChildren) {
3186 layer->detachChildren();
3187 }
3188 if (what & layer_state_t::eOverrideScalingModeChanged) {
3189 layer->setOverrideScalingMode(s.overrideScalingMode);
3190 // We don't trigger a traversal here because if no other state is
3191 // changed, we don't want this to cause any more work
3192 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003193 return flags;
3194}
3195
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003196status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003197 const String8& name,
3198 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003199 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003200 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3201 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003203 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003204 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003205 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003206 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003207 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003208
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003209 status_t result = NO_ERROR;
3210
3211 sp<Layer> layer;
3212
Cody Northropbc755282017-03-31 12:00:08 -06003213 String8 uniqueName = getUniqueLayerName(name);
3214
Mathias Agopian3165cc22012-08-08 19:42:09 -07003215 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3216 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003217 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003218 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003219 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003220
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221 break;
chaviw13fdc492017-06-27 12:40:18 -07003222 case ISurfaceComposerClient::eFXSurfaceColor:
3223 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003224 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003225 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003226 break;
3227 default:
3228 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003229 break;
3230 }
3231
Dan Stoza7d89d062015-04-30 13:29:25 -07003232 if (result != NO_ERROR) {
3233 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003235
Chia-I Wuab0c3192017-08-01 11:29:00 -07003236 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3237 // TODO b/64227542
3238 if (windowType == 441731) {
3239 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3240 layer->setPrimaryDisplayOnly();
3241 }
3242
Albert Chaulk479c60c2017-01-27 14:21:34 -05003243 layer->setInfo(windowType, ownerUid);
3244
Robert Carr1f0a16a2016-10-24 16:27:39 -07003245 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003246 if (result != NO_ERROR) {
3247 return result;
3248 }
Irvelffc9efc2016-07-27 15:16:37 -07003249 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003250
3251 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003252 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003253}
3254
Cody Northropbc755282017-03-31 12:00:08 -06003255String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3256{
3257 bool matchFound = true;
3258 uint32_t dupeCounter = 0;
3259
3260 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3261 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3262
3263 // Loop over layers until we're sure there is no matching name
3264 while (matchFound) {
3265 matchFound = false;
3266 mDrawingState.traverseInZOrder([&](Layer* layer) {
3267 if (layer->getName() == uniqueName) {
3268 matchFound = true;
3269 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3270 }
3271 });
3272 }
3273
3274 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3275
3276 return uniqueName;
3277}
3278
David Sodman0c69cad2017-08-21 12:12:51 -07003279status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003280 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3281 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003282{
3283 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003284 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003285 case PIXEL_FORMAT_TRANSPARENT:
3286 case PIXEL_FORMAT_TRANSLUCENT:
3287 format = PIXEL_FORMAT_RGBA_8888;
3288 break;
3289 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003290 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291 break;
3292 }
3293
David Sodman0c69cad2017-08-21 12:12:51 -07003294 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3295 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003296 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003297 *handle = layer->getHandle();
3298 *gbp = layer->getProducer();
3299 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003300 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003301
David Sodman0c69cad2017-08-21 12:12:51 -07003302 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003303 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003304}
3305
chaviw13fdc492017-06-27 12:40:18 -07003306status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003307 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003308 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003309{
chaviw13fdc492017-06-27 12:40:18 -07003310 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003311 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003312 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003313}
3314
Mathias Agopianac9fa422013-02-11 16:40:36 -08003315status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003316{
Robert Carr9524cb32017-02-13 11:32:32 -08003317 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003318 status_t err = NO_ERROR;
3319 sp<Layer> l(client->getLayerUser(handle));
3320 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003321 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003322 err = removeLayer(l);
3323 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3324 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003325 }
3326 return err;
3327}
3328
Mathias Agopian13127d82013-03-05 17:47:11 -08003329status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003330{
Mathias Agopian67106042013-03-14 19:18:13 -07003331 // called by ~LayerCleaner() when all references to the IBinder (handle)
3332 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003333 sp<Layer> l = layer.promote();
3334 if (l == nullptr) {
3335 // The layer has already been removed, carry on
3336 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003337 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003338 // If we have a parent, then we can continue to live as long as it does.
3339 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003340}
3341
Mathias Agopianb60314a2012-04-10 22:09:54 -07003342// ---------------------------------------------------------------------------
3343
Andy McFadden13a082e2012-08-24 10:16:42 -07003344void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003345 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003346 Vector<ComposerState> state;
3347 Vector<DisplayState> displays;
3348 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003349 d.what = DisplayState::eDisplayProjectionChanged |
3350 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003351 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003352 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003353 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003354 d.frame.makeInvalid();
3355 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003356 d.width = 0;
3357 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003358 displays.add(d);
3359 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003360 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3361 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003362
Dan Stoza9e56aa02015-11-02 13:00:03 -08003363 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3364 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003365 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003366
Brian Andersond0010582017-03-07 13:20:31 -08003367 // Use phase of 0 since phase is not known.
3368 // Use latency of 0, which will snap to the ideal latency.
3369 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003370}
3371
3372void SurfaceFlinger::initializeDisplays() {
3373 class MessageScreenInitialized : public MessageBase {
3374 SurfaceFlinger* flinger;
3375 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003376 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003377 virtual bool handler() {
3378 flinger->onInitializeDisplays();
3379 return true;
3380 }
3381 };
3382 sp<MessageBase> msg = new MessageScreenInitialized(this);
3383 postMessageAsync(msg); // we may be called from main thread, use async message
3384}
3385
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003386void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003387 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003388 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3389 this);
3390 int32_t type = hw->getDisplayType();
3391 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003392
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003393 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003394 return;
3395 }
3396
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003397 hw->setPowerMode(mode);
3398 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3399 ALOGW("Trying to set power mode for virtual display");
3400 return;
3401 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003402
Irvelffc9efc2016-07-27 15:16:37 -07003403 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003404 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003405 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3406 if (idx < 0) {
3407 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3408 return;
3409 }
3410 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3411 }
3412
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003413 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003414 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003415 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003416 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3417 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003418 // FIXME: eventthread only knows about the main display right now
3419 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003420 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003421 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003422
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003423 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003424 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003425 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003426
3427 struct sched_param param = {0};
3428 param.sched_priority = 1;
3429 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3430 ALOGW("Couldn't set SCHED_FIFO on display on");
3431 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003432 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003433 // Turn off the display
3434 struct sched_param param = {0};
3435 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3436 ALOGW("Couldn't set SCHED_OTHER on display off");
3437 }
3438
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003439 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3440 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003441 disableHardwareVsync(true); // also cancels any in-progress resync
3442
Mathias Agopiancde87a32012-09-13 14:09:01 -07003443 // FIXME: eventthread only knows about the main display right now
3444 mEventThread->onScreenReleased();
3445 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003446
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003447 getHwComposer().setPowerMode(type, mode);
3448 mVisibleRegionsDirty = true;
3449 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003450 } else if (mode == HWC_POWER_MODE_DOZE ||
3451 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003452 // Update display while dozing
3453 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003454 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3455 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003456 // FIXME: eventthread only knows about the main display right now
3457 mEventThread->onScreenAcquired();
3458 resyncToHardwareVsync(true);
3459 }
3460 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3461 // Leave display going to doze
3462 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3463 disableHardwareVsync(true); // also cancels any in-progress resync
3464 // FIXME: eventthread only knows about the main display right now
3465 mEventThread->onScreenReleased();
3466 }
3467 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003468 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003469 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003470 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003471 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003472}
3473
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003474void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3475 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003476 SurfaceFlinger& mFlinger;
3477 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003478 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003479 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003480 MessageSetPowerMode(SurfaceFlinger& flinger,
3481 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3482 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003483 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003484 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003485 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003486 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003487 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003488 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003489 ALOGW("Attempt to set power mode = %d for virtual display",
3490 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003491 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003492 mFlinger.setPowerModeInternal(
3493 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003494 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003495 return true;
3496 }
3497 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003498 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003499 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003500}
3501
3502// ---------------------------------------------------------------------------
3503
Vishnu Nair6a408532017-10-24 09:11:27 -07003504status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003505 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003506
Mathias Agopianbd115332013-04-18 16:41:04 -07003507 IPCThreadState* ipc = IPCThreadState::self();
3508 const int pid = ipc->getCallingPid();
3509 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003510
Mathias Agopianbd115332013-04-18 16:41:04 -07003511 if ((uid != AID_SHELL) &&
3512 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003513 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003514 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003515 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003516 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003517 // (this would indicate SF is stuck, but we want to be able to
3518 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003519 status_t err = mStateLock.timedLock(s2ns(1));
3520 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003521 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003522 result.appendFormat(
3523 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3524 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003525 }
3526
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003527 bool dumpAll = true;
3528 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003529 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003530
3531 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003532 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003533 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3534 dumpAll = false;
3535 }
3536
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003537 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003538 if ((index < numArgs) &&
3539 (args[index] == String16("--list"))) {
3540 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003541 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003542 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003543 }
3544
3545 if ((index < numArgs) &&
3546 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003547 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003548 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003549 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003550 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003551
3552 if ((index < numArgs) &&
3553 (args[index] == String16("--latency-clear"))) {
3554 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003555 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003556 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003557 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003558
3559 if ((index < numArgs) &&
3560 (args[index] == String16("--dispsync"))) {
3561 index++;
3562 mPrimaryDispSync.dump(result);
3563 dumpAll = false;
3564 }
Dan Stozab90cf072015-03-05 11:05:59 -08003565
3566 if ((index < numArgs) &&
3567 (args[index] == String16("--static-screen"))) {
3568 index++;
3569 dumpStaticScreenStats(result);
3570 dumpAll = false;
3571 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003572
3573 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003574 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003575 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003576 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003577 dumpAll = false;
3578 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003579
3580 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3581 index++;
3582 dumpWideColorInfo(result);
3583 dumpAll = false;
3584 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003586
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003587 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003588 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003589 }
3590
Mathias Agopian9795c422009-08-26 16:36:26 -07003591 if (locked) {
3592 mStateLock.unlock();
3593 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003594 }
3595 write(fd, result.string(), result.size());
3596 return NO_ERROR;
3597}
3598
Dan Stozac7014012014-02-14 15:03:43 -08003599void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3600 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003601{
Robert Carr2047fae2016-11-28 14:09:09 -08003602 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003603 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003604 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003605}
3606
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003607void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003608 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003609{
3610 String8 name;
3611 if (index < args.size()) {
3612 name = String8(args[index]);
3613 index++;
3614 }
3615
Dan Stoza9e56aa02015-11-02 13:00:03 -08003616 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3617 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003618 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003619
3620 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003621 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003622 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003623 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003624 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003625 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003626 }
Robert Carr2047fae2016-11-28 14:09:09 -08003627 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003628 }
3629}
3630
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003631void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003632 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003633{
3634 String8 name;
3635 if (index < args.size()) {
3636 name = String8(args[index]);
3637 index++;
3638 }
3639
Robert Carr2047fae2016-11-28 14:09:09 -08003640 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003641 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003642 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003643 }
Robert Carr2047fae2016-11-28 14:09:09 -08003644 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003645
Svetoslavd85084b2014-03-20 10:28:31 -07003646 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003647}
3648
Jamie Gennis6547ff42013-07-16 20:12:42 -07003649// This should only be called from the main thread. Otherwise it would need
3650// the lock and should use mCurrentState rather than mDrawingState.
3651void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003652 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003653 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003654 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003655
3656 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3657}
3658
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003659void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003660{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003661 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003662 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3663
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003664 if (isLayerTripleBufferingDisabled())
3665 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003666
3667 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003668 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003669 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003670 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003671 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3672 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003673 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003674}
3675
Dan Stozab90cf072015-03-05 11:05:59 -08003676void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3677{
3678 result.appendFormat("Static screen stats:\n");
3679 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3680 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3681 float percent = 100.0f *
3682 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3683 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3684 b + 1, bucketTimeSec, percent);
3685 }
3686 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3687 float percent = 100.0f *
3688 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3689 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3690 NUM_BUCKETS - 1, bucketTimeSec, percent);
3691}
3692
Dan Stozae77c7662016-05-13 11:37:28 -07003693void SurfaceFlinger::recordBufferingStats(const char* layerName,
3694 std::vector<OccupancyTracker::Segment>&& history) {
3695 Mutex::Autolock lock(mBufferingStatsMutex);
3696 auto& stats = mBufferingStats[layerName];
3697 for (const auto& segment : history) {
3698 if (!segment.usedThirdBuffer) {
3699 stats.twoBufferTime += segment.totalTime;
3700 }
3701 if (segment.occupancyAverage < 1.0f) {
3702 stats.doubleBufferedTime += segment.totalTime;
3703 } else if (segment.occupancyAverage < 2.0f) {
3704 stats.tripleBufferedTime += segment.totalTime;
3705 }
3706 ++stats.numSegments;
3707 stats.totalTime += segment.totalTime;
3708 }
3709}
3710
Brian Andersond6927fb2016-07-23 23:37:30 -07003711void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3712 result.appendFormat("Layer frame timestamps:\n");
3713
3714 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3715 const size_t count = currentLayers.size();
3716 for (size_t i=0 ; i<count ; i++) {
3717 currentLayers[i]->dumpFrameEvents(result);
3718 }
3719}
3720
Dan Stozae77c7662016-05-13 11:37:28 -07003721void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3722 result.append("Buffering stats:\n");
3723 result.append(" [Layer name] <Active time> <Two buffer> "
3724 "<Double buffered> <Triple buffered>\n");
3725 Mutex::Autolock lock(mBufferingStatsMutex);
3726 typedef std::tuple<std::string, float, float, float> BufferTuple;
3727 std::map<float, BufferTuple, std::greater<float>> sorted;
3728 for (const auto& statsPair : mBufferingStats) {
3729 const char* name = statsPair.first.c_str();
3730 const BufferingStats& stats = statsPair.second;
3731 if (stats.numSegments == 0) {
3732 continue;
3733 }
3734 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3735 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3736 stats.totalTime;
3737 float doubleBufferRatio = static_cast<float>(
3738 stats.doubleBufferedTime) / stats.totalTime;
3739 float tripleBufferRatio = static_cast<float>(
3740 stats.tripleBufferedTime) / stats.totalTime;
3741 sorted.insert({activeTime, {name, twoBufferRatio,
3742 doubleBufferRatio, tripleBufferRatio}});
3743 }
3744 for (const auto& sortedPair : sorted) {
3745 float activeTime = sortedPair.first;
3746 const BufferTuple& values = sortedPair.second;
3747 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3748 std::get<0>(values).c_str(), activeTime,
3749 std::get<1>(values), std::get<2>(values),
3750 std::get<3>(values));
3751 }
3752 result.append("\n");
3753}
3754
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003755void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3756 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003757 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003758
3759 // TODO: print out if wide-color mode is active or not
3760
3761 for (size_t d = 0; d < mDisplays.size(); d++) {
3762 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3763 int32_t hwcId = displayDevice->getHwcDisplayId();
3764 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3765 continue;
3766 }
3767
3768 result.appendFormat("Display %d color modes:\n", hwcId);
3769 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3770 for (auto&& mode : modes) {
3771 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3772 }
3773
3774 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3775 result.appendFormat(" Current color mode: %s (%d)\n",
3776 decodeColorMode(currentMode).c_str(), currentMode);
3777 }
3778 result.append("\n");
3779}
3780
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003781LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003782 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003783 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3784 const State& state = useDrawing ? mDrawingState : mCurrentState;
3785 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003786 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003787 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003788 });
3789
3790 return layersProto;
3791}
3792
Mathias Agopian74d211a2013-04-22 16:55:35 +02003793void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3794 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003795{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003796 bool colorize = false;
3797 if (index < args.size()
3798 && (args[index] == String16("--color"))) {
3799 colorize = true;
3800 index++;
3801 }
3802
3803 Colorizer colorizer(colorize);
3804
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003805 // figure out if we're stuck somewhere
3806 const nsecs_t now = systemTime();
3807 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3808 const nsecs_t inTransaction(mDebugInTransaction);
3809 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3810 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3811
3812 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003813 * Dump library configuration.
3814 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003815
3816 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003817 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003818 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003819 appendSfConfigString(result);
3820 appendUiConfigString(result);
3821 appendGuiConfigString(result);
3822 result.append("\n");
3823
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003824 result.append("\nWide-Color information:\n");
3825 dumpWideColorInfo(result);
3826
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003827 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003828 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003829 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003830 result.append(SyncFeatures::getInstance().toString());
3831 result.append("\n");
3832
Dan Stoza9e56aa02015-11-02 13:00:03 -08003833 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3834
Andy McFadden41d67d72014-04-25 16:58:34 -07003835 colorizer.bold(result);
3836 result.append("DispSync configuration: ");
3837 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003838 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003839 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003840 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003841 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003842 result.append("\n");
3843
Dan Stozab90cf072015-03-05 11:05:59 -08003844 // Dump static screen stats
3845 result.append("\n");
3846 dumpStaticScreenStats(result);
3847 result.append("\n");
3848
Dan Stozae77c7662016-05-13 11:37:28 -07003849 dumpBufferingStats(result);
3850
Andy McFadden4803b742012-09-24 19:07:20 -07003851 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003852 * Dump the visible layer list
3853 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003854 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003855 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003856 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003857
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003858 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003859 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3860 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003861
3862 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003863 * Dump Display state
3864 */
3865
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003866 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003867 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003868 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003869 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3870 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003871 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003872 }
3873
3874 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003875 * Dump SurfaceFlinger global state
3876 */
3877
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003878 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003879 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003880 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003881
Mathias Agopian888c8222012-08-04 21:10:38 -07003882 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003883 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003884
Mathias Agopian875d8e12013-06-07 15:35:48 -07003885 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003886
Mathias Agopian42977342012-08-05 00:40:46 -07003887 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003888 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3889 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003890 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003891 " last eglSwapBuffers() time: %f us\n"
3892 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003893 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003894 " refresh-rate : %f fps\n"
3895 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003896 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003897 " gpu_to_cpu_unsupported : %d\n"
3898 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003899 mLastSwapBufferTime/1000.0,
3900 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003901 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003902 1e9 / activeConfig->getVsyncPeriod(),
3903 activeConfig->getDpiX(),
3904 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003905 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003906
Mathias Agopian74d211a2013-04-22 16:55:35 +02003907 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003908 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003909
Mathias Agopian74d211a2013-04-22 16:55:35 +02003910 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003911 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003912
3913 /*
3914 * VSYNC state
3915 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003916 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003917 result.append("\n");
3918
3919 /*
3920 * HWC layer minidump
3921 */
3922 for (size_t d = 0; d < mDisplays.size(); d++) {
3923 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3924 int32_t hwcId = displayDevice->getHwcDisplayId();
3925 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3926 continue;
3927 }
3928
3929 result.appendFormat("Display %d HWC layers:\n", hwcId);
3930 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003931 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003932 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003933 });
Dan Stozae22aec72016-08-01 13:20:59 -07003934 result.append("\n");
3935 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003936
3937 /*
3938 * Dump HWComposer state
3939 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003940 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003941 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003942 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003943 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003944 result.appendFormat(" h/w composer %s\n",
3945 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003946 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003947
3948 /*
3949 * Dump gralloc state
3950 */
3951 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3952 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003953
3954 /*
3955 * Dump VrFlinger state if in use.
3956 */
3957 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3958 result.append("VrFlinger state:\n");
3959 result.append(mVrFlinger->Dump().c_str());
3960 result.append("\n");
3961 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003962}
3963
Mathias Agopian13127d82013-03-05 17:47:11 -08003964const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003965SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003966 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003967 wp<IBinder> dpy;
3968 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3969 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3970 dpy = mDisplays.keyAt(i);
3971 break;
3972 }
3973 }
3974 if (dpy == NULL) {
3975 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3976 // Just use the primary display so we have something to return
3977 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3978 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003979 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003980}
3981
Keun young Park63f165f2012-08-31 10:53:36 -07003982bool SurfaceFlinger::startDdmConnection()
3983{
3984 void* libddmconnection_dso =
3985 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3986 if (!libddmconnection_dso) {
3987 return false;
3988 }
3989 void (*DdmConnection_start)(const char* name);
3990 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003991 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003992 if (!DdmConnection_start) {
3993 dlclose(libddmconnection_dso);
3994 return false;
3995 }
3996 (*DdmConnection_start)(getServiceName());
3997 return true;
3998}
3999
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004000status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004001 switch (code) {
4002 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004003 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004004 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004005 case CLEAR_ANIMATION_FRAME_STATS:
4006 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004007 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004008 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004009 case ENABLE_VSYNC_INJECTIONS:
4010 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004011 {
4012 // codes that require permission check
4013 IPCThreadState* ipc = IPCThreadState::self();
4014 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004015 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004016 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004017 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004018 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004019 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004020 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004021 break;
4022 }
Robert Carr1db73f62016-12-21 12:58:51 -08004023 /*
4024 * Calling setTransactionState is safe, because you need to have been
4025 * granted a reference to Client* and Handle* to do anything with it.
4026 *
4027 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4028 */
4029 case SET_TRANSACTION_STATE:
4030 case CREATE_SCOPED_CONNECTION:
4031 {
4032 return OK;
4033 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004034 case CAPTURE_SCREEN:
4035 {
4036 // codes that require permission check
4037 IPCThreadState* ipc = IPCThreadState::self();
4038 const int pid = ipc->getCallingPid();
4039 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004040 if ((uid != AID_GRAPHICS) &&
4041 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004042 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004043 return PERMISSION_DENIED;
4044 }
4045 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004046 }
chaviwa76b2712017-09-20 12:02:26 -07004047 case CAPTURE_LAYERS: {
4048 IPCThreadState* ipc = IPCThreadState::self();
4049 const int pid = ipc->getCallingPid();
4050 const int uid = ipc->getCallingUid();
4051 if ((uid != AID_GRAPHICS) &&
4052 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4053 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4054 return PERMISSION_DENIED;
4055 }
4056 break;
4057 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004058 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004059 return OK;
4060}
4061
4062status_t SurfaceFlinger::onTransact(
4063 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4064{
4065 status_t credentialCheck = CheckTransactCodeCredentials(code);
4066 if (credentialCheck != OK) {
4067 return credentialCheck;
4068 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004069
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004070 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4071 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004072 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004073 IPCThreadState* ipc = IPCThreadState::self();
4074 const int uid = ipc->getCallingUid();
4075 if (CC_UNLIKELY(uid != AID_SYSTEM
4076 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004077 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004078 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004079 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004080 return PERMISSION_DENIED;
4081 }
4082 int n;
4083 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004084 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004085 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004086 return NO_ERROR;
4087 case 1002: // SHOW_UPDATES
4088 n = data.readInt32();
4089 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004090 invalidateHwcGeometry();
4091 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004092 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004093 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004094 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004095 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004096 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004097 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004098 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004099 setTransactionFlags(
4100 eTransactionNeeded|
4101 eDisplayTransactionNeeded|
4102 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004103 return NO_ERROR;
4104 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004105 case 1006:{ // send empty update
4106 signalRefresh();
4107 return NO_ERROR;
4108 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004109 case 1008: // toggle use of hw composer
4110 n = data.readInt32();
4111 mDebugDisableHWC = n ? 1 : 0;
4112 invalidateHwcGeometry();
4113 repaintEverything();
4114 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004115 case 1009: // toggle use of transform hint
4116 n = data.readInt32();
4117 mDebugDisableTransformHint = n ? 1 : 0;
4118 invalidateHwcGeometry();
4119 repaintEverything();
4120 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004121 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004122 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004123 reply->writeInt32(0);
4124 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004125 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004126 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004127 return NO_ERROR;
4128 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004129 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004130 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004131 return NO_ERROR;
4132 }
4133 case 1014: {
4134 // daltonize
4135 n = data.readInt32();
4136 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004137 case 1:
4138 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4139 break;
4140 case 2:
4141 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4142 break;
4143 case 3:
4144 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4145 break;
4146 default:
4147 mDaltonizer.setType(ColorBlindnessType::None);
4148 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004149 }
4150 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004151 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004152 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004153 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004154 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004155 invalidateHwcGeometry();
4156 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004157 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004158 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004159 case 1015: {
4160 // apply a color matrix
4161 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004162 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004163 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004164 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004165 for (size_t j = 0; j < 4; j++) {
4166 mColorMatrix[i][j] = data.readFloat();
4167 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004168 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004169 } else {
4170 mColorMatrix = mat4();
4171 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004172
4173 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4174 // the division by w in the fragment shader
4175 float4 lastRow(transpose(mColorMatrix)[3]);
4176 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4177 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4178 }
4179
Alan Viverette9c5a3332013-09-12 20:04:35 -07004180 invalidateHwcGeometry();
4181 repaintEverything();
4182 return NO_ERROR;
4183 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004184 // This is an experimental interface
4185 // Needs to be shifted to proper binder interface when we productize
4186 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004187 n = data.readInt32();
4188 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004189 return NO_ERROR;
4190 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004191 case 1017: {
4192 n = data.readInt32();
4193 mForceFullDamage = static_cast<bool>(n);
4194 return NO_ERROR;
4195 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004196 case 1018: { // Modify Choreographer's phase offset
4197 n = data.readInt32();
4198 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4199 return NO_ERROR;
4200 }
4201 case 1019: { // Modify SurfaceFlinger's phase offset
4202 n = data.readInt32();
4203 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4204 return NO_ERROR;
4205 }
Irvel468051e2016-06-13 16:44:44 -07004206 case 1020: { // Layer updates interceptor
4207 n = data.readInt32();
4208 if (n) {
4209 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004210 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004211 }
4212 else{
4213 ALOGV("Interceptor disabled");
4214 mInterceptor.disable();
4215 }
4216 return NO_ERROR;
4217 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004218 case 1021: { // Disable HWC virtual displays
4219 n = data.readInt32();
4220 mUseHwcVirtualDisplays = !n;
4221 return NO_ERROR;
4222 }
Romain Guy0147a172017-06-01 13:53:56 -07004223 case 1022: { // Set saturation boost
4224 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4225
4226 invalidateHwcGeometry();
4227 repaintEverything();
4228 return NO_ERROR;
4229 }
Romain Guy54f154a2017-10-24 21:40:32 +01004230 case 1023: { // Set native mode
4231 mForceNativeColorMode = data.readInt32() == 1;
4232
4233 invalidateHwcGeometry();
4234 repaintEverything();
4235 return NO_ERROR;
4236 }
4237 case 1024: { // Is wide color gamut rendering/color management supported?
4238 reply->writeBool(hasWideColorDisplay);
4239 return NO_ERROR;
4240 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004241 case 1025: { // tracing
4242 n = data.readInt32();
4243 if (n) {
4244 ALOGV("LayerTracing enabled");
4245 mTracing.enable();
4246 doTracing("tracing.enable");
4247 reply->writeInt32(NO_ERROR);
4248 } else {
4249 ALOGV("LayerTracing disabled");
4250 status_t err = mTracing.disable();
4251 reply->writeInt32(err);
4252 }
4253 return NO_ERROR;
4254 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004255 }
4256 }
4257 return err;
4258}
4259
Steven Thomas6d8110b2017-08-31 18:24:21 -07004260void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004261 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004262 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004263}
4264
Steven Thomas6d8110b2017-08-31 18:24:21 -07004265void SurfaceFlinger::repaintEverything() {
4266 ConditionalLock _l(mStateLock,
4267 std::this_thread::get_id() != mMainThreadId);
4268 repaintEverythingLocked();
4269}
4270
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004271// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4272class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004273public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004274 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4275 ~WindowDisconnector() {
4276 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004277 }
4278
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004279private:
4280 ANativeWindow* mWindow;
4281 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004282};
4283
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004284static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4285 uint32_t requestedHeight, bool hasWideColorDisplay,
4286 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4287 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4288 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4289
4290 int err = 0;
4291 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4292 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4293 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4294 err |= native_window_set_usage(window, usage);
4295
4296 if (hasWideColorDisplay) {
4297 err |= native_window_set_buffers_data_space(window,
4298 renderEngineUsesWideColor
4299 ? HAL_DATASPACE_DISPLAY_P3
4300 : HAL_DATASPACE_V0_SRGB);
4301 }
4302
4303 if (err != NO_ERROR) {
4304 return BAD_VALUE;
4305 }
4306
4307 /* TODO: Once we have the sync framework everywhere this can use
4308 * server-side waits on the fence that dequeueBuffer returns.
4309 */
4310 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4311 if (err != NO_ERROR) {
4312 return err;
4313 }
4314
4315 return NO_ERROR;
4316}
4317
4318status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4319 const sp<IGraphicBufferProducer>& producer, Rect sourceCrop,
4320 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4321 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004322 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004323 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004324
chaviwa76b2712017-09-20 12:02:26 -07004325 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4326
4327 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4328 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4329
4330 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4331 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004332 return captureScreenCommon(renderArea, traverseLayers, producer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004333}
4334
4335status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004336 const sp<IGraphicBufferProducer>& producer,
4337 const Rect& sourceCrop, float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004338 ATRACE_CALL();
4339
4340 class LayerRenderArea : public RenderArea {
4341 public:
chaviw7206d492017-11-10 16:16:12 -08004342 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004343 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004344 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004345 const Transform& getTransform() const override {
4346 // Make the top level transform the inverse the transform and it's parent so it sets
4347 // the whole capture back to 0,0
4348 return *new Transform(mLayer->getTransform().inverse());
4349 }
4350 Rect getBounds() const override {
4351 const Layer::State& layerState(mLayer->getDrawingState());
4352 return Rect(layerState.active.w, layerState.active.h);
4353 }
4354 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4355 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4356 bool isSecure() const override { return false; }
4357 bool needsFiltering() const override { return false; }
4358
chaviw7206d492017-11-10 16:16:12 -08004359 Rect getSourceCrop() const override {
4360 if (mCrop.isEmpty()) {
4361 return getBounds();
4362 } else {
4363 return mCrop;
4364 }
4365 }
chaviwa76b2712017-09-20 12:02:26 -07004366 bool getWideColorSupport() const override { return false; }
4367 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4368
4369 private:
chaviw7206d492017-11-10 16:16:12 -08004370 const sp<Layer> mLayer;
4371 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004372 };
4373
4374 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4375 auto parent = layerHandle->owner.promote();
4376
chaviw7206d492017-11-10 16:16:12 -08004377 if (parent == nullptr || parent->isPendingRemoval()) {
4378 ALOGE("captureLayers called with a removed parent");
4379 return NAME_NOT_FOUND;
4380 }
4381
4382 Rect crop(sourceCrop);
4383 if (sourceCrop.width() <= 0) {
4384 crop.left = 0;
4385 crop.right = parent->getCurrentState().active.w;
4386 }
4387
4388 if (sourceCrop.height() <= 0) {
4389 crop.top = 0;
4390 crop.bottom = parent->getCurrentState().active.h;
4391 }
4392
4393 int32_t reqWidth = crop.width() * frameScale;
4394 int32_t reqHeight = crop.height() * frameScale;
4395
4396 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4397
chaviwa76b2712017-09-20 12:02:26 -07004398 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4399 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4400 if (!layer->isVisible()) {
4401 return;
4402 }
4403 visitor(layer);
4404 });
4405 };
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004406 return captureScreenCommon(renderArea, traverseLayers, producer, false);
chaviwa76b2712017-09-20 12:02:26 -07004407}
4408
4409status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4410 TraverseLayersFunction traverseLayers,
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004411 const sp<IGraphicBufferProducer>& producer,
chaviwa76b2712017-09-20 12:02:26 -07004412 bool useIdentityTransform) {
4413 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004414
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004415 if (CC_UNLIKELY(producer == 0))
4416 return BAD_VALUE;
4417
chaviwa76b2712017-09-20 12:02:26 -07004418 renderArea.updateDimensions();
4419
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004420 // if we have secure windows on this display, never allow the screen capture
4421 // unless the producer interface is local (i.e.: we can take a screenshot for
4422 // ourselves).
4423 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
4424
4425 // create a surface (because we're a producer, and we need to
4426 // dequeue/queue a buffer)
4427 sp<Surface> surface = new Surface(producer, false);
4428
4429 // Put the screenshot Surface into async mode so that
4430 // Layer::headFenceHasSignaled will always return true and we'll latch the
4431 // first buffer regardless of whether or not its acquire fence has
4432 // signaled. This is needed to avoid a race condition in the rotation
4433 // animation. See b/30209608
4434 surface->setAsyncMode(true);
4435
4436 ANativeWindow* window = surface.get();
4437
4438 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4439 if (result != NO_ERROR) {
4440 return result;
4441 }
4442 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4443
4444 ANativeWindowBuffer* buffer = nullptr;
4445 result = getWindowBuffer(window, renderArea.getReqWidth(), renderArea.getReqHeight(),
4446 hasWideColorDisplay && !mForceNativeColorMode,
4447 getRenderEngine().usesWideColor(), &buffer);
4448 if (result != NO_ERROR) {
4449 return result;
4450 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004451
4452 // This mutex protects syncFd and captureResult for communication of the return values from the
4453 // main thread back to this Binder thread
4454 std::mutex captureMutex;
4455 std::condition_variable captureCondition;
4456 std::unique_lock<std::mutex> captureLock(captureMutex);
4457 int syncFd = -1;
4458 std::optional<status_t> captureResult;
4459
4460 sp<LambdaMessage> message = new LambdaMessage([&]() {
4461 // If there is a refresh pending, bug out early and tell the binder thread to try again
4462 // after the refresh.
4463 if (mRefreshPending) {
4464 ATRACE_NAME("Skipping screenshot for now");
4465 std::unique_lock<std::mutex> captureLock(captureMutex);
4466 captureResult = std::make_optional<status_t>(EAGAIN);
4467 captureCondition.notify_one();
4468 return;
4469 }
4470
4471 status_t result = NO_ERROR;
4472 int fd = -1;
4473 {
4474 Mutex::Autolock _l(mStateLock);
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004475 result = captureScreenImplLocked(renderArea, traverseLayers, buffer,
4476 useIdentityTransform, isLocalScreenshot, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004477 }
4478
4479 {
4480 std::unique_lock<std::mutex> captureLock(captureMutex);
4481 syncFd = fd;
4482 captureResult = std::make_optional<status_t>(result);
4483 captureCondition.notify_one();
4484 }
4485 });
4486
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004487 result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004488 if (result == NO_ERROR) {
4489 captureCondition.wait(captureLock, [&]() { return captureResult; });
4490 while (*captureResult == EAGAIN) {
4491 captureResult.reset();
4492 result = postMessageAsync(message);
4493 if (result != NO_ERROR) {
4494 return result;
4495 }
4496 captureCondition.wait(captureLock, [&]() { return captureResult; });
4497 }
4498 result = *captureResult;
4499 }
4500
4501 if (result == NO_ERROR) {
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004502 // queueBuffer takes ownership of syncFd
4503 result = window->queueBuffer(window, buffer, syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004504 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004505 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004506}
4507
chaviwa76b2712017-09-20 12:02:26 -07004508void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4509 TraverseLayersFunction traverseLayers, bool yswap,
4510 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004511 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004512
Mathias Agopian3f844832013-08-07 21:24:32 -07004513 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004514
4515 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004516 const auto raWidth = renderArea.getWidth();
4517 const auto raHeight = renderArea.getHeight();
4518
4519 const auto reqWidth = renderArea.getReqWidth();
4520 const auto reqHeight = renderArea.getReqHeight();
4521 Rect sourceCrop = renderArea.getSourceCrop();
4522
4523 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4524 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004525
Dan Stozac1879002014-05-22 15:59:05 -07004526 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004527 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004528 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004529 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004530 }
4531
4532 // ensure that sourceCrop is inside screen
4533 if (sourceCrop.left < 0) {
4534 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4535 }
chaviwa76b2712017-09-20 12:02:26 -07004536 if (sourceCrop.right > raWidth) {
4537 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004538 }
4539 if (sourceCrop.top < 0) {
4540 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4541 }
chaviwa76b2712017-09-20 12:02:26 -07004542 if (sourceCrop.bottom > raHeight) {
4543 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004544 }
4545
chaviwa76b2712017-09-20 12:02:26 -07004546 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004547 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004548
Mathias Agopian180f10d2013-04-10 22:55:41 -07004549 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004550 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004551
4552 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004553 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4554 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004555 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004556
4557 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004558 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004559
chaviwa76b2712017-09-20 12:02:26 -07004560 traverseLayers([&](Layer* layer) {
4561 if (filtering) layer->setFiltering(true);
4562 layer->draw(renderArea, useIdentityTransform);
4563 if (filtering) layer->setFiltering(false);
4564 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004565}
4566
chaviwa76b2712017-09-20 12:02:26 -07004567status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4568 TraverseLayersFunction traverseLayers,
4569 ANativeWindowBuffer* buffer,
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004570 bool useIdentityTransform, bool isLocalScreenshot,
chaviwa76b2712017-09-20 12:02:26 -07004571 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004572 ATRACE_CALL();
4573
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004574 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004575
4576 traverseLayers([&](Layer* layer) {
4577 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4578 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004579
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004580 if (!isLocalScreenshot && secureLayerIsVisible) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004581 ALOGW("FB is protected: PERMISSION_DENIED");
4582 return PERMISSION_DENIED;
4583 }
4584
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004585 // this binds the given EGLImage as a framebuffer for the
4586 // duration of this scope.
Chia-I Wueadbaa62017-11-09 11:26:15 -08004587 RenderEngine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
4588 if (bufferBond.getStatus() != NO_ERROR) {
4589 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004590 return INVALID_OPERATION;
4591 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004592
Dan Stozaabcda352017-06-01 14:37:39 -07004593 // this will in fact render into our dequeued buffer
4594 // via an FBO, which means we didn't have to create
4595 // an EGLSurface and therefore we're not
4596 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004597 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004598
Chia-I Wub0c041b2017-11-09 11:36:33 -08004599 *outSyncFd = getRenderEngine().flush(DEBUG_SCREENSHOTS);
Dan Stozaabcda352017-06-01 14:37:39 -07004600
4601 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004602 const auto reqWidth = renderArea.getReqWidth();
4603 const auto reqHeight = renderArea.getReqHeight();
4604
Dan Stozaabcda352017-06-01 14:37:39 -07004605 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4606 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004607 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004608 delete [] pixels;
4609 }
4610
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004611 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004612}
4613
Mathias Agopiand5556842013-09-19 17:08:37 -07004614void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004615 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004616 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004617 for (size_t y = 0; y < h; y++) {
4618 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4619 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004620 if (p[x] != 0xFF000000) return;
4621 }
4622 }
chaviwa76b2712017-09-20 12:02:26 -07004623 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004624
Robert Carr2047fae2016-11-28 14:09:09 -08004625 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004626 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004627 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004628 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4629 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4630 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4631 static_cast<float>(state.color.a));
4632 i++;
4633 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004634 }
4635}
4636
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004637// ---------------------------------------------------------------------------
4638
Dan Stoza412903f2017-04-27 13:42:17 -07004639void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4640 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004641}
4642
Dan Stoza412903f2017-04-27 13:42:17 -07004643void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4644 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004645}
4646
chaviwa76b2712017-09-20 12:02:26 -07004647void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4648 int32_t maxLayerZ,
4649 const LayerVector::Visitor& visitor) {
4650 // We loop through the first level of layers without traversing,
4651 // as we need to interpret min/max layer Z in the top level Z space.
4652 for (const auto& layer : mDrawingState.layersSortedByZ) {
4653 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4654 continue;
4655 }
4656 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004657 // relative layers are traversed in Layer::traverseInZOrder
4658 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004659 continue;
4660 }
4661 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4662 if (!layer->isVisible()) {
4663 return;
4664 }
4665 visitor(layer);
4666 });
4667 }
4668}
4669
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004670}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004671
4672
4673#if defined(__gl_h_)
4674#error "don't include gl/gl.h in this file"
4675#endif
4676
4677#if defined(__gl2_h_)
4678#error "don't include gl2/gl2.h in this file"
Chavi Weingarten707b8f32017-11-29 21:25:51 +00004679#endif