blob: 815944e9b79577cf633595ba0d166973a365075c [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
31#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080040#include <dvr/vr_flinger.h>
41
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060042#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070044#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070045
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080049#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080050#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051
52#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080055
Mathias Agopiancde87a32012-09-13 14:09:01 -070056#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/String8.h>
58#include <utils/String16.h>
59#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070060#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian921e6ac2012-07-23 23:11:29 -070063#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070064#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070070#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
David Sodman0c69cad2017-08-21 12:12:51 -070075#include "BufferLayer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070076#include "LayerVector.h"
chaviw13fdc492017-06-27 12:40:18 -070077#include "ColorLayer.h"
Robert Carr1db73f62016-12-21 12:58:51 -080078#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Steven Thomasb02664d2017-07-26 18:48:28 -070081#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include "Effects/Daltonizer.h"
87
Mathias Agopian875d8e12013-06-07 15:35:48 -070088#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070090
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090092#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090093
chaviw1d044282017-09-27 12:19:28 -070094#include <layerproto/LayerProtoParser.h>
95
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080096#define DISPLAY_COUNT 1
97
Mathias Agopianfee2b462013-07-03 12:34:01 -070098/*
99 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
100 * black pixels.
101 */
102#define DEBUG_SCREENSHOTS false
103
Jiyong Park00b15b82017-08-10 20:30:56 +0900104extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
Mathias Agopianca088332013-03-28 17:44:13 -0700105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107
Jaesoo Lee43518572017-01-23 19:03:16 +0900108using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109using namespace android::hardware::configstore::V1_0;
110
Steven Thomasb02664d2017-07-26 18:48:28 -0700111namespace {
112class ConditionalLock {
113public:
114 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
115 if (lock) {
116 mMutex.lock();
117 }
118 }
119 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
120private:
121 Mutex& mMutex;
122 bool mLocked;
123};
124} // namespace anonymous
125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126// ---------------------------------------------------------------------------
127
Mathias Agopian99b49842011-06-27 16:05:52 -0700128const String16 sHardwareTest("android.permission.HARDWARE_TEST");
129const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
130const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
131const String16 sDump("android.permission.DUMP");
132
133// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800134int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
135int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700136bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700137int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700138bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800139uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800140bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800141bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800142int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600143bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700144
Kalle Raitaa099a242017-01-11 11:17:29 -0800145
146std::string getHwcServiceName() {
147 char value[PROPERTY_VALUE_MAX] = {};
148 property_get("debug.sf.hwc_service_name", value, "default");
149 ALOGI("Using HWComposer service: '%s'", value);
150 return std::string(value);
151}
152
153bool useTrebleTestingOverride() {
154 char value[PROPERTY_VALUE_MAX] = {};
155 property_get("debug.sf.treble_testing_override", value, "false");
156 ALOGI("Treble testing override: '%s'", value);
157 return std::string(value) == "true";
158}
159
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700161 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700163 mTransactionPending(false),
164 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700165 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700166 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700167 mRepaintEverything(0),
Kalle Raitaa099a242017-01-11 11:17:29 -0800168 mHwcServiceName(getHwcServiceName()),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800169 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800170 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800171 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800172 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800173 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800174 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700176 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700177 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700178 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700179 mDebugInSwapBuffers(0),
180 mLastSwapBufferTime(0),
181 mDebugInTransaction(0),
182 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700183 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700184 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800185 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000186 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700187 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700188 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700189 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800190 mHasPoweredOff(false),
191 mFrameBuckets(),
192 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700193 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800194 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700195 mVrFlingerRequestsDisplay(false),
196 mMainThreadId(std::this_thread::get_id()),
197 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800198{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800199 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800200
201 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
202 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
203
204 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
205 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
206
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800207 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
208 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700210 useContextPriority = getBool< ISurfaceFlingerConfigs,
211 &ISurfaceFlingerConfigs::useContextPriority>(false);
212
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700213 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
214 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
215
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700216 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
217 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
218
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800219 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
220 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
221
Steven Thomas050b2c82017-03-06 11:45:16 -0800222 // Vr flinger is only enabled on Daydream ready devices.
223 useVrFlinger = getBool< ISurfaceFlingerConfigs,
224 &ISurfaceFlingerConfigs::useVrFlinger>(false);
225
Fabien Sanglard1971b632017-03-10 14:50:03 -0800226 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
227 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
228
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600229 hasWideColorDisplay =
230 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
231
Saurabh Shahf4174532017-07-13 10:45:07 -0700232 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
233
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234 // debugging stuff...
235 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700236
Mathias Agopianb4b17302013-03-20 18:36:41 -0700237 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700238 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700239
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240 property_get("debug.sf.showupdates", value, "0");
241 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700242
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700243 property_get("debug.sf.ddms", value, "0");
244 mDebugDDMS = atoi(value);
245 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700246 if (!startDdmConnection()) {
247 // start failed, and DDMS debugging not enabled
248 mDebugDDMS = 0;
249 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700250 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700251 ALOGI_IF(mDebugRegion, "showupdates enabled");
252 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700253
254 property_get("debug.sf.disable_backpressure", value, "0");
255 mPropagateBackpressure = !atoi(value);
256 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700257
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800258 property_get("debug.sf.enable_hwc_vds", value, "0");
259 mUseHwcVirtualDisplays = atoi(value);
260 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800261
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800262 property_get("ro.sf.disable_triple_buffer", value, "1");
263 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800264 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700265
Romain Guy11d63f42017-07-20 12:47:14 -0700266 // We should be reading 'persist.sys.sf.color_saturation' here
267 // but since /data may be encrypted, we need to wait until after vold
268 // comes online to attempt to read the property. The property is
269 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800270
271 if (useTrebleTestingOverride()) {
272 // Without the override SurfaceFlinger cannot connect to HIDL
273 // services that are not listed in the manifests. Considered
274 // deriving the setting from the set service name, but it
275 // would be brittle if the name that's not 'default' is used
276 // for production purposes later on.
277 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
278 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800279}
280
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800281void SurfaceFlinger::onFirstRef()
282{
283 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800284}
285
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286SurfaceFlinger::~SurfaceFlinger()
287{
Mathias Agopiana4912602012-07-12 14:25:33 -0700288 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
289 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
290 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291}
292
Dan Stozac7014012014-02-14 15:03:43 -0800293void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800294{
295 // the window manager died on us. prepare its eulogy.
296
Andy McFadden13a082e2012-08-24 10:16:42 -0700297 // restore initial conditions (default device unblank, etc)
298 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800299
300 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700301 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800302}
303
Robert Carr1db73f62016-12-21 12:58:51 -0800304static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700305 status_t err = client->initCheck();
306 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800307 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800308 }
Robert Carr1db73f62016-12-21 12:58:51 -0800309 return nullptr;
310}
311
312sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
313 return initClient(new Client(this));
314}
315
316sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
317 const sp<IGraphicBufferProducer>& gbp) {
318 if (authenticateSurfaceTexture(gbp) == false) {
319 return nullptr;
320 }
321 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
322 if (layer == nullptr) {
323 return nullptr;
324 }
325
326 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800327}
328
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700329sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
330 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700331{
332 class DisplayToken : public BBinder {
333 sp<SurfaceFlinger> flinger;
334 virtual ~DisplayToken() {
335 // no more references, this display must be terminated
336 Mutex::Autolock _l(flinger->mStateLock);
337 flinger->mCurrentState.displays.removeItem(this);
338 flinger->setTransactionFlags(eDisplayTransactionNeeded);
339 }
340 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700341 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700342 : flinger(flinger) {
343 }
344 };
345
346 sp<BBinder> token = new DisplayToken(this);
347
348 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700349 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700350 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700351 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700352 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700353 return token;
354}
355
Jesse Hall6c913be2013-08-08 12:15:49 -0700356void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
357 Mutex::Autolock _l(mStateLock);
358
359 ssize_t idx = mCurrentState.displays.indexOfKey(display);
360 if (idx < 0) {
361 ALOGW("destroyDisplay: invalid display token");
362 return;
363 }
364
365 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
366 if (!info.isVirtualDisplay()) {
367 ALOGE("destroyDisplay called for non-virtual display");
368 return;
369 }
Irvelffc9efc2016-07-27 15:16:37 -0700370 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700371 mCurrentState.displays.removeItemsAt(idx);
372 setTransactionFlags(eDisplayTransactionNeeded);
373}
374
Jesse Hall692c7232012-11-08 15:41:56 -0800375void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800376 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800377 ALOGW_IF(mBuiltinDisplays[type],
378 "Overwriting display token for display type %d", type);
379 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800380 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700381 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800382 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700383 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800384}
385
Mathias Agopiane57f2922012-08-09 16:29:12 -0700386sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700387 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700388 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
389 return NULL;
390 }
Jesse Hall692c7232012-11-08 15:41:56 -0800391 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700392}
393
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800394void SurfaceFlinger::bootFinished()
395{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700396 if (mStartPropertySetThread->join() != NO_ERROR) {
397 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800398 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399 const nsecs_t now = systemTime();
400 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000401 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700402
403 // wait patiently for the window manager death
404 const String16 name("window");
405 sp<IBinder> window(defaultServiceManager()->getService(name));
406 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700407 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700408 }
409
Steven Thomas050b2c82017-03-06 11:45:16 -0800410 if (mVrFlinger) {
411 mVrFlinger->OnBootFinished();
412 }
413
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700414 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700415 // formerly we would just kill the process, but we now ask it to exit so it
416 // can choose where to stop the animation.
417 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700418
419 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
420 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
421 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700422
Thierry Strudel2924d012017-08-14 15:19:37 -0700423 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700424 readPersistentProperties();
425 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700426 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427}
428
Mathias Agopian3f844832013-08-07 21:24:32 -0700429void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700430 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700431 RenderEngine& engine;
432 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700433 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700434 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
435 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700436 }
437 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700438 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700439 return true;
440 }
441 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700442 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700443}
444
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700445class DispSyncSource : public VSyncSource, private DispSync::Callback {
446public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700447 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000448 const char* name) :
449 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700450 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700451 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000452 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
453 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700454 mDispSync(dispSync),
455 mCallbackMutex(),
456 mCallback(),
457 mVsyncMutex(),
458 mPhaseOffset(phaseOffset),
459 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700460
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700461 virtual ~DispSyncSource() {}
462
463 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700464 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700465 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000466 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700467 static_cast<DispSync::Callback*>(this));
468 if (err != NO_ERROR) {
469 ALOGE("error registering vsync callback: %s (%d)",
470 strerror(-err), err);
471 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700472 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700473 } else {
474 status_t err = mDispSync->removeEventListener(
475 static_cast<DispSync::Callback*>(this));
476 if (err != NO_ERROR) {
477 ALOGE("error unregistering vsync callback: %s (%d)",
478 strerror(-err), err);
479 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700480 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700482 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700483 }
484
485 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700486 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 mCallback = callback;
488 }
489
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700490 virtual void setPhaseOffset(nsecs_t phaseOffset) {
491 Mutex::Autolock lock(mVsyncMutex);
492
493 // Normalize phaseOffset to [0, period)
494 auto period = mDispSync->getPeriod();
495 phaseOffset %= period;
496 if (phaseOffset < 0) {
497 // If we're here, then phaseOffset is in (-period, 0). After this
498 // operation, it will be in (0, period)
499 phaseOffset += period;
500 }
501 mPhaseOffset = phaseOffset;
502
503 // If we're not enabled, we don't need to mess with the listeners
504 if (!mEnabled) {
505 return;
506 }
507
508 // Remove the listener with the old offset
509 status_t err = mDispSync->removeEventListener(
510 static_cast<DispSync::Callback*>(this));
511 if (err != NO_ERROR) {
512 ALOGE("error unregistering vsync callback: %s (%d)",
513 strerror(-err), err);
514 }
515
516 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000517 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700518 static_cast<DispSync::Callback*>(this));
519 if (err != NO_ERROR) {
520 ALOGE("error registering vsync callback: %s (%d)",
521 strerror(-err), err);
522 }
523 }
524
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525private:
526 virtual void onDispSyncEvent(nsecs_t when) {
527 sp<VSyncSource::Callback> callback;
528 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700529 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530 callback = mCallback;
531
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700532 if (mTraceVsync) {
533 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700534 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700535 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536 }
537
538 if (callback != NULL) {
539 callback->onVSyncEvent(when);
540 }
541 }
542
Tim Murray4a4e4a22016-04-19 16:29:23 +0000543 const char* const mName;
544
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700545 int mValue;
546
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700547 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700548 const String8 mVsyncOnLabel;
549 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700550
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700551 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700552
553 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700554 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700555
556 Mutex mVsyncMutex; // Protects the following
557 nsecs_t mPhaseOffset;
558 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700559};
560
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700561class InjectVSyncSource : public VSyncSource {
562public:
563 InjectVSyncSource() {}
564
565 virtual ~InjectVSyncSource() {}
566
567 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
568 std::lock_guard<std::mutex> lock(mCallbackMutex);
569 mCallback = callback;
570 }
571
572 virtual void onInjectSyncEvent(nsecs_t when) {
573 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700574 if (mCallback) {
575 mCallback->onVSyncEvent(when);
576 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700577 }
578
579 virtual void setVSyncEnabled(bool) {}
580 virtual void setPhaseOffset(nsecs_t) {}
581
582private:
583 std::mutex mCallbackMutex; // Protects the following
584 sp<VSyncSource::Callback> mCallback;
585};
586
Wei Wangf9b05ee2017-07-19 20:59:39 -0700587// Do not call property_set on main thread which will be blocked by init
588// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700590 ALOGI( "SurfaceFlinger's main thread ready to run. "
591 "Initializing graphics H/W...");
592
Thierry Strudel2924d012017-08-14 15:19:37 -0700593 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900594
Steven Thomasb02664d2017-07-26 18:48:28 -0700595 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800596
Steven Thomasb02664d2017-07-26 18:48:28 -0700597 // start the EventThread
598 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
599 vsyncPhaseOffsetNs, true, "app");
600 mEventThread = new EventThread(vsyncSrc, *this, false);
601 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
602 sfVsyncPhaseOffsetNs, true, "sf");
603 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
604 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800605
Steven Thomasb02664d2017-07-26 18:48:28 -0700606 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
607 struct sched_param param = {0};
608 param.sched_priority = 2;
609 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
610 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
611 }
612 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
613 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800614 }
615
Steven Thomasb02664d2017-07-26 18:48:28 -0700616 // Get a RenderEngine for the given display / config (can't fail)
Chia-I Wud4d9c6f2017-11-09 16:55:31 -0800617 mRenderEngine = RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
Steven Thomasb02664d2017-07-26 18:48:28 -0700618 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Chia-I Wud4d9c6f2017-11-09 16:55:31 -0800619 LOG_ALWAYS_FATAL_IF(mRenderEngine == nullptr, "couldn't create RenderEngine");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800620
Chia-I Wud4d9c6f2017-11-09 16:55:31 -0800621 // retrieve the EGL display/context that was selected/created
622 mEGLDisplay = mRenderEngine->getEGLDisplay();
Steven Thomasb02664d2017-07-26 18:48:28 -0700623 mEGLContext = mRenderEngine->getEGLContext();
624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
626 "Starting with vr flinger active is not currently supported.");
627 mHwc.reset(new HWComposer(mHwcServiceName));
628 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800629
Steven Thomas050b2c82017-03-06 11:45:16 -0800630 if (useVrFlinger) {
631 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700632 // This callback is called from the vr flinger dispatch thread. We
633 // need to call signalTransaction(), which requires holding
634 // mStateLock when we're not on the main thread. Acquiring
635 // mStateLock from the vr flinger dispatch thread might trigger a
636 // deadlock in surface flinger (see b/66916578), so post a message
637 // to be handled on the main thread instead.
638 sp<LambdaMessage> message = new LambdaMessage([=]() {
639 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
640 mVrFlingerRequestsDisplay = requestDisplay;
641 signalTransaction();
642 });
643 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800644 };
645 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800646 mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
647 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800648 if (!mVrFlinger) {
649 ALOGE("Failed to start vrflinger");
650 }
651 }
652
Jamie Gennisd1700752013-10-14 12:22:52 -0700653 mEventControlThread = new EventControlThread(this);
654 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
655
Mathias Agopian92a979a2012-08-02 18:32:23 -0700656 // initialize our drawing state
657 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700658
Andy McFadden13a082e2012-08-24 10:16:42 -0700659 // set initial conditions (e.g. unblank default device)
660 initializeDisplays();
661
Dan Stoza4e637772016-07-28 13:31:51 -0700662 mRenderEngine->primeCache();
663
Wei Wangf9b05ee2017-07-19 20:59:39 -0700664 // Inform native graphics APIs whether the present timestamp is supported:
665 if (getHwComposer().hasCapability(
666 HWC2::Capability::PresentFenceIsNotReliable)) {
667 mStartPropertySetThread = new StartPropertySetThread(false);
668 } else {
669 mStartPropertySetThread = new StartPropertySetThread(true);
670 }
671
672 if (mStartPropertySetThread->Start() != NO_ERROR) {
673 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800674 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800675
Dan Stoza9e56aa02015-11-02 13:00:03 -0800676 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700677}
678
Romain Guy11d63f42017-07-20 12:47:14 -0700679void SurfaceFlinger::readPersistentProperties() {
680 char value[PROPERTY_VALUE_MAX];
681
682 property_get("persist.sys.sf.color_saturation", value, "1.0");
683 mSaturation = atof(value);
684 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100685
686 property_get("persist.sys.sf.native_mode", value, "0");
687 mForceNativeColorMode = atoi(value) == 1;
688 if (mForceNativeColorMode) {
689 ALOGV("Forcing native color mode");
690 }
Romain Guy11d63f42017-07-20 12:47:14 -0700691}
692
Mathias Agopiana67e4182012-06-19 17:26:12 -0700693void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800694 // Start boot animation service by setting a property mailbox
695 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700696 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800697 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 if (mStartPropertySetThread->join() != NO_ERROR) {
699 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800700 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700701}
702
Mathias Agopian875d8e12013-06-07 15:35:48 -0700703size_t SurfaceFlinger::getMaxTextureSize() const {
704 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700705}
706
Mathias Agopian875d8e12013-06-07 15:35:48 -0700707size_t SurfaceFlinger::getMaxViewportDims() const {
708 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700709}
710
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800711// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800712
Jamie Gennis582270d2011-08-17 18:19:00 -0700713bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800714 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800715 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800716 return authenticateSurfaceTextureLocked(bufferProducer);
717}
718
719bool SurfaceFlinger::authenticateSurfaceTextureLocked(
720 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800721 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700722 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800723}
724
Brian Anderson6b376712017-04-04 10:51:39 -0700725status_t SurfaceFlinger::getSupportedFrameTimestamps(
726 std::vector<FrameEvent>* outSupported) const {
727 *outSupported = {
728 FrameEvent::REQUESTED_PRESENT,
729 FrameEvent::ACQUIRE,
730 FrameEvent::LATCH,
731 FrameEvent::FIRST_REFRESH_START,
732 FrameEvent::LAST_REFRESH_START,
733 FrameEvent::GPU_COMPOSITION_DONE,
734 FrameEvent::DEQUEUE_READY,
735 FrameEvent::RELEASE,
736 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700737 ConditionalLock _l(mStateLock,
738 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700739 if (!getHwComposer().hasCapability(
740 HWC2::Capability::PresentFenceIsNotReliable)) {
741 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
742 }
743 return NO_ERROR;
744}
745
Dan Stoza7f7da322014-05-02 15:26:25 -0700746status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
747 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700748 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700749 return BAD_VALUE;
750 }
751
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500752 if (!display.get())
753 return NAME_NOT_FOUND;
754
Jesse Hall692c7232012-11-08 15:41:56 -0800755 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700756 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800757 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700758 type = i;
759 break;
760 }
761 }
762
763 if (type < 0) {
764 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700765 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700766
Mathias Agopian8b736f12012-08-13 17:54:26 -0700767 // TODO: Not sure if display density should handled by SF any longer
768 class Density {
769 static int getDensityFromProperty(char const* propName) {
770 char property[PROPERTY_VALUE_MAX];
771 int density = 0;
772 if (property_get(propName, property, NULL) > 0) {
773 density = atoi(property);
774 }
775 return density;
776 }
777 public:
778 static int getEmuDensity() {
779 return getDensityFromProperty("qemu.sf.lcd_density"); }
780 static int getBuildDensity() {
781 return getDensityFromProperty("ro.sf.lcd_density"); }
782 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700783
Dan Stoza7f7da322014-05-02 15:26:25 -0700784 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700785
Steven Thomas6d8110b2017-08-31 18:24:21 -0700786 ConditionalLock _l(mStateLock,
787 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800788 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700789 DisplayInfo info = DisplayInfo();
790
Dan Stoza9e56aa02015-11-02 13:00:03 -0800791 float xdpi = hwConfig->getDpiX();
792 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700793
794 if (type == DisplayDevice::DISPLAY_PRIMARY) {
795 // The density of the device is provided by a build property
796 float density = Density::getBuildDensity() / 160.0f;
797 if (density == 0) {
798 // the build doesn't provide a density -- this is wrong!
799 // use xdpi instead
800 ALOGE("ro.sf.lcd_density must be defined as a build property");
801 density = xdpi / 160.0f;
802 }
803 if (Density::getEmuDensity()) {
804 // if "qemu.sf.lcd_density" is specified, it overrides everything
805 xdpi = ydpi = density = Density::getEmuDensity();
806 density /= 160.0f;
807 }
808 info.density = density;
809
810 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700811 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000812 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 } else {
814 // TODO: where should this value come from?
815 static const int TV_DENSITY = 213;
816 info.density = TV_DENSITY / 160.0f;
817 info.orientation = 0;
818 }
819
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820 info.w = hwConfig->getWidth();
821 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 info.xdpi = xdpi;
823 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800824 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900825 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826
Andy McFadden91b2ca82014-06-13 14:04:23 -0700827 // This is how far in advance a buffer must be queued for
828 // presentation at a given time. If you want a buffer to appear
829 // on the screen at time N, you must submit the buffer before
830 // (N - presentationDeadline).
831 //
832 // Normally it's one full refresh period (to give SF a chance to
833 // latch the buffer), but this can be reduced by configuring a
834 // DispSync offset. Any additional delays introduced by the hardware
835 // composer or panel must be accounted for here.
836 //
837 // We add an additional 1ms to allow for processing time and
838 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800839 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800840 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700841
842 // All non-virtual displays are currently considered secure.
843 info.secure = true;
844
Michael Wright28f24d02016-07-12 13:30:53 -0700845 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846 }
847
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 return NO_ERROR;
849}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700850
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800851status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700852 DisplayStatInfo* stats) {
853 if (stats == NULL) {
854 return BAD_VALUE;
855 }
856
857 // FIXME for now we always return stats for the primary display
858 memset(stats, 0, sizeof(*stats));
859 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
860 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
861 return NO_ERROR;
862}
863
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700864int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800865 if (display == NULL) {
866 ALOGE("%s : display is NULL", __func__);
867 return BAD_VALUE;
868 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700869
870 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700871 if (device != NULL) {
872 return device->getActiveConfig();
873 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700874
Dan Stoza24a42e92015-03-09 10:04:11 -0700875 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700876}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700877
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700878void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
879 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
880 this);
881 int32_t type = hw->getDisplayType();
882 int currentMode = hw->getActiveConfig();
883
884 if (mode == currentMode) {
885 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
886 return;
887 }
888
889 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
890 ALOGW("Trying to set config for virtual display");
891 return;
892 }
893
894 hw->setActiveConfig(mode);
895 getHwComposer().setActiveConfig(type, mode);
896}
897
898status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
899 class MessageSetActiveConfig: public MessageBase {
900 SurfaceFlinger& mFlinger;
901 sp<IBinder> mDisplay;
902 int mMode;
903 public:
904 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
905 int mode) :
906 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
907 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700908 Vector<DisplayInfo> configs;
909 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700910 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700911 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700912 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700913 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700914 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700915 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
916 if (hw == NULL) {
917 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700918 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700919 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
920 ALOGW("Attempt to set active config = %d for virtual display",
921 mMode);
922 } else {
923 mFlinger.setActiveConfigInternal(hw, mMode);
924 }
925 return true;
926 }
927 };
928 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
929 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700930 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700931}
Michael Wright28f24d02016-07-12 13:30:53 -0700932status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
933 Vector<android_color_mode_t>* outColorModes) {
934 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
935 return BAD_VALUE;
936 }
937
938 if (!display.get()) {
939 return NAME_NOT_FOUND;
940 }
941
942 int32_t type = NAME_NOT_FOUND;
943 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
944 if (display == mBuiltinDisplays[i]) {
945 type = i;
946 break;
947 }
948 }
949
950 if (type < 0) {
951 return type;
952 }
953
Steven Thomas6d8110b2017-08-31 18:24:21 -0700954 std::vector<android_color_mode_t> modes;
955 {
956 ConditionalLock _l(mStateLock,
957 std::this_thread::get_id() != mMainThreadId);
958 modes = getHwComposer().getColorModes(type);
959 }
Michael Wright28f24d02016-07-12 13:30:53 -0700960 outColorModes->clear();
961 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
962
963 return NO_ERROR;
964}
965
966android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700967 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700968 if (device != nullptr) {
969 return device->getActiveColorMode();
970 }
971 return static_cast<android_color_mode_t>(BAD_VALUE);
972}
973
974void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
975 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700976 int32_t type = hw->getDisplayType();
977 android_color_mode_t currentMode = hw->getActiveColorMode();
978
979 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700980 return;
981 }
982
983 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
984 ALOGW("Trying to set config for virtual display");
985 return;
986 }
987
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600988 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
989 hw->getDisplayType());
990
Michael Wright28f24d02016-07-12 13:30:53 -0700991 hw->setActiveColorMode(mode);
992 getHwComposer().setActiveColorMode(type, mode);
993}
994
995
996status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
997 android_color_mode_t colorMode) {
998 class MessageSetActiveColorMode: public MessageBase {
999 SurfaceFlinger& mFlinger;
1000 sp<IBinder> mDisplay;
1001 android_color_mode_t mMode;
1002 public:
1003 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1004 android_color_mode_t mode) :
1005 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1006 virtual bool handler() {
1007 Vector<android_color_mode_t> modes;
1008 mFlinger.getDisplayColorModes(mDisplay, &modes);
1009 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1010 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001011 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1012 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001013 return true;
1014 }
1015 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1016 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001017 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1018 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001019 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001020 ALOGW("Attempt to set active color mode %s %d for virtual display",
1021 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001022 } else {
1023 mFlinger.setActiveColorModeInternal(hw, mMode);
1024 }
1025 return true;
1026 }
1027 };
1028 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1029 postMessageSync(msg);
1030 return NO_ERROR;
1031}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001032
Svetoslavd85084b2014-03-20 10:28:31 -07001033status_t SurfaceFlinger::clearAnimationFrameStats() {
1034 Mutex::Autolock _l(mStateLock);
1035 mAnimFrameTracker.clearStats();
1036 return NO_ERROR;
1037}
1038
1039status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1040 Mutex::Autolock _l(mStateLock);
1041 mAnimFrameTracker.getStats(outStats);
1042 return NO_ERROR;
1043}
1044
Dan Stozac4f471e2016-03-24 09:31:08 -07001045status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1046 HdrCapabilities* outCapabilities) const {
1047 Mutex::Autolock _l(mStateLock);
1048
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001049 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001050 if (displayDevice == nullptr) {
1051 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1052 return BAD_VALUE;
1053 }
1054
1055 std::unique_ptr<HdrCapabilities> capabilities =
1056 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1057 if (capabilities) {
1058 std::swap(*outCapabilities, *capabilities);
1059 } else {
1060 return BAD_VALUE;
1061 }
1062
1063 return NO_ERROR;
1064}
1065
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001066status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001067 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1068 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001069
Chia-I Wu90f669f2017-10-05 14:24:41 -07001070 if (mInjectVSyncs == enable) {
1071 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001072 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001073
1074 if (enable) {
1075 ALOGV("VSync Injections enabled");
1076 if (mVSyncInjector.get() == nullptr) {
1077 mVSyncInjector = new InjectVSyncSource();
1078 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1079 }
1080 mEventQueue.setEventThread(mInjectorEventThread);
1081 } else {
1082 ALOGV("VSync Injections disabled");
1083 mEventQueue.setEventThread(mSFEventThread);
1084 }
1085
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001086 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001087 });
1088 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001089 return NO_ERROR;
1090}
1091
1092status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001093 Mutex::Autolock _l(mStateLock);
1094
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095 if (!mInjectVSyncs) {
1096 ALOGE("VSync Injections not enabled");
1097 return BAD_VALUE;
1098 }
1099 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1100 ALOGV("Injecting VSync inside SurfaceFlinger");
1101 mVSyncInjector->onInjectSyncEvent(when);
1102 }
1103 return NO_ERROR;
1104}
1105
Kalle Raitaa099a242017-01-11 11:17:29 -08001106status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1107 IPCThreadState* ipc = IPCThreadState::self();
1108 const int pid = ipc->getCallingPid();
1109 const int uid = ipc->getCallingUid();
1110 if ((uid != AID_SHELL) &&
1111 !PermissionCache::checkPermission(sDump, pid, uid)) {
1112 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1113 return PERMISSION_DENIED;
1114 }
1115
1116 // Try to acquire a lock for 1s, fail gracefully
1117 const status_t err = mStateLock.timedLock(s2ns(1));
1118 const bool locked = (err == NO_ERROR);
1119 if (!locked) {
1120 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1121 return TIMED_OUT;
1122 }
1123
1124 outLayers->clear();
1125 mCurrentState.traverseInZOrder([&](Layer* layer) {
1126 outLayers->push_back(layer->getLayerDebugInfo());
1127 });
1128
1129 mStateLock.unlock();
1130 return NO_ERROR;
1131}
1132
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001133// ----------------------------------------------------------------------------
1134
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001135sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1136 ISurfaceComposer::VsyncSource vsyncSource) {
1137 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1138 return mSFEventThread->createEventConnection();
1139 } else {
1140 return mEventThread->createEventConnection();
1141 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001142}
1143
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001144// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001145
1146void SurfaceFlinger::waitForEvent() {
1147 mEventQueue.waitMessage();
1148}
1149
1150void SurfaceFlinger::signalTransaction() {
1151 mEventQueue.invalidate();
1152}
1153
1154void SurfaceFlinger::signalLayerUpdate() {
1155 mEventQueue.invalidate();
1156}
1157
1158void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001159 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001160 mEventQueue.refresh();
1161}
1162
1163status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001164 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001165 return mEventQueue.postMessage(msg, reltime);
1166}
1167
1168status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001169 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001170 status_t res = mEventQueue.postMessage(msg, reltime);
1171 if (res == NO_ERROR) {
1172 msg->wait();
1173 }
1174 return res;
1175}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001177void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001178 do {
1179 waitForEvent();
1180 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001181}
1182
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001183void SurfaceFlinger::enableHardwareVsync() {
1184 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001185 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001187 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1188 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001190 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001191}
1192
Jesse Hall948fe0c2013-10-14 12:56:09 -07001193void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194 Mutex::Autolock _l(mHWVsyncLock);
1195
Jesse Hall948fe0c2013-10-14 12:56:09 -07001196 if (makeAvailable) {
1197 mHWVsyncAvailable = true;
1198 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001199 // Hardware vsync is not currently available, so abort the resync
1200 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001201 return;
1202 }
1203
Dan Stoza9e56aa02015-11-02 13:00:03 -08001204 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1205 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001206
1207 mPrimaryDispSync.reset();
1208 mPrimaryDispSync.setPeriod(period);
1209
1210 if (!mPrimaryHWVsyncEnabled) {
1211 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001212 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1213 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001214 mPrimaryHWVsyncEnabled = true;
1215 }
1216}
1217
Jesse Hall948fe0c2013-10-14 12:56:09 -07001218void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001219 Mutex::Autolock _l(mHWVsyncLock);
1220 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001221 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1222 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223 mPrimaryDispSync.endResync();
1224 mPrimaryHWVsyncEnabled = false;
1225 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001226 if (makeUnavailable) {
1227 mHWVsyncAvailable = false;
1228 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001229}
1230
Tim Murray4a4e4a22016-04-19 16:29:23 +00001231void SurfaceFlinger::resyncWithRateLimit() {
1232 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001233
1234 // No explicit locking is needed here since EventThread holds a lock while calling this method
1235 static nsecs_t sLastResyncAttempted = 0;
1236 const nsecs_t now = systemTime();
1237 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001238 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001239 }
Dan Stoza57164302017-05-08 14:03:54 -07001240 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001241}
1242
Steven Thomasb02664d2017-07-26 18:48:28 -07001243void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1244 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001245 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001246 // Ignore any vsyncs from a previous hardware composer.
1247 if (sequenceId != mComposerSequenceId) {
1248 return;
1249 }
1250
1251 int32_t type;
1252 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001253 return;
1254 }
1255
Jamie Gennisd1700752013-10-14 12:22:52 -07001256 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001257
Jamie Gennisd1700752013-10-14 12:22:52 -07001258 { // Scope for the lock
1259 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001260 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001261 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001263 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001264
1265 if (needsHwVsync) {
1266 enableHardwareVsync();
1267 } else {
1268 disableHardwareVsync(false);
1269 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001270}
1271
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001272void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001273 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001274 *compositorTiming = mCompositorTiming;
1275}
1276
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001277void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001278 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001279 wp<IBinder> token = mBuiltinDisplays[type];
1280
1281 // All non-virtual displays are currently considered secure.
1282 const bool isSecure = true;
1283
1284 sp<IGraphicBufferProducer> producer;
1285 sp<IGraphicBufferConsumer> consumer;
1286 BufferQueue::createBufferQueue(&producer, &consumer);
1287
1288 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1289
1290 bool hasWideColorModes = false;
1291 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1292 for (android_color_mode_t colorMode : modes) {
1293 switch (colorMode) {
1294 case HAL_COLOR_MODE_DISPLAY_P3:
1295 case HAL_COLOR_MODE_ADOBE_RGB:
1296 case HAL_COLOR_MODE_DCI_P3:
1297 hasWideColorModes = true;
1298 break;
1299 default:
1300 break;
1301 }
1302 }
Romain Guy54f154a2017-10-24 21:40:32 +01001303 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001304 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1305 token, fbs, producer, mRenderEngine->getEGLConfig(),
Romain Guy54f154a2017-10-24 21:40:32 +01001306 useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001307 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001308 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001309 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001310 defaultColorMode = HAL_COLOR_MODE_SRGB;
1311 }
1312 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001313 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001314
1315 // Add the primary display token to mDrawingState so we don't try to
1316 // recreate the DisplayDevice for the primary display.
1317 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1318
1319 // make the GLContext current so that we can create textures when creating
1320 // Layers (which may happens before we render something)
1321 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001322}
1323
Steven Thomasb02664d2017-07-26 18:48:28 -07001324void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1325 hwc2_display_t display, HWC2::Connection connection,
1326 bool primaryDisplay) {
1327 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1328 sequenceId, display,
1329 connection == HWC2::Connection::Connected ?
1330 "connected" : "disconnected",
1331 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001332
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 // Only lock if we're not on the main thread. This function is normally
1334 // called on a hwbinder thread, but for the primary display it's called on
1335 // the main thread with the state lock already held, so don't attempt to
1336 // acquire it here.
1337 ConditionalLock lock(mStateLock,
1338 std::this_thread::get_id() != mMainThreadId);
1339
1340 if (primaryDisplay) {
1341 mHwc->onHotplug(display, connection);
1342 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1343 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001344 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001345 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001346 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001347 if (sequenceId != mComposerSequenceId) {
1348 return;
1349 }
1350 if (mHwc->isUsingVrComposer()) {
1351 ALOGE("External displays are not supported by the vr hardware composer.");
1352 return;
1353 }
1354 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001355 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001356 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001357 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001358 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001359 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1360 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001361 }
1362 setTransactionFlags(eDisplayTransactionNeeded);
1363
Andy McFadden9e9689c2012-10-10 18:17:51 -07001364 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001365 }
Mathias Agopian86303202012-07-24 22:46:10 -07001366}
1367
Steven Thomasb02664d2017-07-26 18:48:28 -07001368void SurfaceFlinger::onRefreshReceived(int sequenceId,
1369 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001370 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 if (sequenceId != mComposerSequenceId) {
1372 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001373 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001374 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001375}
1376
Dan Stoza9e56aa02015-11-02 13:00:03 -08001377void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001378 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001380 getHwComposer().setVsyncEnabled(disp,
1381 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001382}
1383
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001384// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001385void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001386 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387 // Clear the drawing state so that the logic inside of
1388 // handleTransactionLocked will fire. It will determine the delta between
1389 // mCurrentState and mDrawingState and re-apply all changes when we make the
1390 // transition.
1391 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001392 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001393 mDisplays.clear();
1394}
1395
Steven Thomas050b2c82017-03-06 11:45:16 -08001396void SurfaceFlinger::updateVrFlinger() {
1397 if (!mVrFlinger)
1398 return;
1399 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1400 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001401 return;
1402 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001403
Steven Thomasb02664d2017-07-26 18:48:28 -07001404 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1405 ALOGE("Vr flinger is only supported for remote hardware composer"
1406 " service connections. Ignoring request to transition to vr"
1407 " flinger.");
1408 mVrFlingerRequestsDisplay = false;
1409 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001410 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001411
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001412 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001413
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 int currentDisplayPowerMode = getDisplayDeviceLocked(
1415 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416
Steven Thomasb02664d2017-07-26 18:48:28 -07001417 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001420
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 resetDisplayState();
1422 mHwc.reset(); // Delete the current instance before creating the new one
1423 mHwc.reset(new HWComposer(
1424 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1425 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1428 "Switched to non-remote hardware composer");
1429
1430 if (vrFlingerRequestsDisplay) {
1431 mVrFlinger->GrantDisplayOwnership();
1432 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001433 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001435
1436 mVisibleRegionsDirty = true;
1437 invalidateHwcGeometry();
1438
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001439 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1441 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1442 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001443
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 // Reset the timing values to account for the period of the swapped in HWC
1445 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1446 const nsecs_t period = activeConfig->getVsyncPeriod();
1447 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001448
Steven Thomasb02664d2017-07-26 18:48:28 -07001449 // Use phase of 0 since phase is not known.
1450 // Use latency of 0, which will snap to the ideal latency.
1451 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001452
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001453 android_atomic_or(1, &mRepaintEverything);
1454 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001455}
1456
Mathias Agopian4fec8732012-06-29 14:12:52 -07001457void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001458 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001459 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001460 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001461 bool frameMissed = !mHadClientComposition &&
1462 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001463 (mPreviousPresentFence->getSignalTime() ==
1464 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001465 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001466 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001467 signalLayerUpdate();
1468 break;
1469 }
1470
Steven Thomas050b2c82017-03-06 11:45:16 -08001471 // Now that we're going to make it to the handleMessageTransaction()
1472 // call below it's safe to call updateVrFlinger(), which will
1473 // potentially trigger a display handoff.
1474 updateVrFlinger();
1475
Dan Stoza6b9454d2014-11-07 16:00:59 -08001476 bool refreshNeeded = handleMessageTransaction();
1477 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001478 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001479 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001480 // Signal a refresh if a transaction modified the window state,
1481 // a new buffer was latched, or if HWC has requested a full
1482 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001483 signalRefresh();
1484 }
1485 break;
1486 }
1487 case MessageQueue::REFRESH: {
1488 handleMessageRefresh();
1489 break;
1490 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001491 }
1492}
1493
Dan Stoza6b9454d2014-11-07 16:00:59 -08001494bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001495 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001496 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001497 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001498 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001499 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001500 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001501}
1502
Dan Stoza6b9454d2014-11-07 16:00:59 -08001503bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001504 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001505 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001506}
1507
1508void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001510
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001511 mRefreshPending = false;
1512
Pablo Ceballos40845df2016-01-25 17:41:15 -08001513 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001514
Brian Andersond6927fb2016-07-23 23:37:30 -07001515 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001516 rebuildLayerStacks();
1517 setUpHWComposer();
1518 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001519 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001520 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001521 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001522
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001523 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001524
1525 mHadClientComposition = false;
1526 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1527 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1528 mHadClientComposition = mHadClientComposition ||
1529 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1530 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001531
Dan Stoza9e56aa02015-11-02 13:00:03 -08001532 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001533}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001534
Mathias Agopiancd60f992012-08-16 16:28:27 -07001535void SurfaceFlinger::doDebugFlashRegions()
1536{
1537 // is debugging enabled
1538 if (CC_LIKELY(!mDebugRegion))
1539 return;
1540
1541 const bool repaintEverything = mRepaintEverything;
1542 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1543 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001544 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545 // transform the dirty region into this screen's coordinate space
1546 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1547 if (!dirtyRegion.isEmpty()) {
1548 // redraw the whole screen
1549 doComposeSurfaces(hw, Region(hw->bounds()));
1550
1551 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001552 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001553 RenderEngine& engine(getRenderEngine());
1554 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1555
Mathias Agopianda27af92012-09-13 18:17:13 -07001556 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557 }
1558 }
1559 }
1560
1561 postFramebuffer();
1562
1563 if (mDebugRegion > 1) {
1564 usleep(mDebugRegion * 1000);
1565 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001566
Dan Stoza9e56aa02015-11-02 13:00:03 -08001567 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001568 auto& displayDevice = mDisplays[displayId];
1569 if (!displayDevice->isDisplayOn()) {
1570 continue;
1571 }
1572
1573 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001574 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1575 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001576 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577}
1578
Adrian Roos1e1a1282017-11-01 19:05:31 +01001579void SurfaceFlinger::doTracing(const char* where) {
1580 ATRACE_CALL();
1581 ATRACE_NAME(where);
1582 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001583 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001584 }
1585}
1586
Brian Andersond6927fb2016-07-23 23:37:30 -07001587void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001589 ATRACE_CALL();
1590 ALOGV("preComposition");
1591
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001593 mDrawingState.traverseInZOrder([&](Layer* layer) {
1594 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001595 needExtraInvalidate = true;
1596 }
Robert Carr2047fae2016-11-28 14:09:09 -08001597 });
1598
Mathias Agopiancd60f992012-08-16 16:28:27 -07001599 if (needExtraInvalidate) {
1600 signalLayerUpdate();
1601 }
1602}
1603
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001604void SurfaceFlinger::updateCompositorTiming(
1605 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1606 std::shared_ptr<FenceTime>& presentFenceTime) {
1607 // Update queue of past composite+present times and determine the
1608 // most recently known composite to present latency.
1609 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1610 nsecs_t compositeToPresentLatency = -1;
1611 while (!mCompositePresentTimes.empty()) {
1612 CompositePresentTime& cpt = mCompositePresentTimes.front();
1613 // Cached values should have been updated before calling this method,
1614 // which helps avoid duplicate syscalls.
1615 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1616 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1617 break;
1618 }
1619 compositeToPresentLatency = displayTime - cpt.composite;
1620 mCompositePresentTimes.pop();
1621 }
1622
1623 // Don't let mCompositePresentTimes grow unbounded, just in case.
1624 while (mCompositePresentTimes.size() > 16) {
1625 mCompositePresentTimes.pop();
1626 }
1627
Brian Andersond0010582017-03-07 13:20:31 -08001628 setCompositorTimingSnapped(
1629 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1630}
1631
1632void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1633 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634 // Integer division and modulo round toward 0 not -inf, so we need to
1635 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001636 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001637 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1638 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1639
Brian Andersond0010582017-03-07 13:20:31 -08001640 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1641 if (idealLatency <= 0) {
1642 idealLatency = vsyncInterval;
1643 }
1644
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001645 // Snap the latency to a value that removes scheduling jitter from the
1646 // composition and present times, which often have >1ms of jitter.
1647 // Reducing jitter is important if an app attempts to extrapolate
1648 // something (such as user input) to an accurate diasplay time.
1649 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1650 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001651 nsecs_t bias = vsyncInterval / 2;
1652 int64_t extraVsyncs =
1653 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1654 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1655 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656
Brian Andersond0010582017-03-07 13:20:31 -08001657 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001658 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1659 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001660 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001661}
1662
1663void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001664{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001665 ATRACE_CALL();
1666 ALOGV("postComposition");
1667
Brian Anderson3546a3f2016-07-14 11:51:14 -07001668 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001669 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001670 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001671 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001672 }
1673
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001674 // |mStateLock| not needed as we are on the main thread
1675 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001676
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001677 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001678 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1679 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1680 glCompositionDoneFenceTime =
1681 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1682 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1683 } else {
1684 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1685 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001686
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001687 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001688 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1689 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1690 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001691
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001692 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1693 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1694
1695 // We use the refreshStartTime which might be sampled a little later than
1696 // when we started doing work for this frame, but that should be okay
1697 // since updateCompositorTiming has snapping logic.
1698 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001699 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001700 CompositorTiming compositorTiming;
1701 {
1702 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1703 compositorTiming = mCompositorTiming;
1704 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001705
Robert Carr2047fae2016-11-28 14:09:09 -08001706 mDrawingState.traverseInZOrder([&](Layer* layer) {
1707 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001708 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001709 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001710 recordBufferingStats(layer->getName().string(),
1711 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001712 }
Robert Carr2047fae2016-11-28 14:09:09 -08001713 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001714
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001715 if (presentFenceTime->isValid()) {
1716 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001717 enableHardwareVsync();
1718 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001719 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001720 }
1721 }
1722
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001723 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001724 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001725 enableHardwareVsync();
1726 }
1727 }
1728
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001729 if (mAnimCompositionPending) {
1730 mAnimCompositionPending = false;
1731
Brian Anderson4e606e32017-03-16 15:34:57 -07001732 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001733 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001734 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001735 } else {
1736 // The HWC doesn't support present fences, so use the refresh
1737 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001738 nsecs_t presentTime =
1739 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001740 mAnimFrameTracker.setActualPresentTime(presentTime);
1741 }
1742 mAnimFrameTracker.advanceFrame();
1743 }
Dan Stozab90cf072015-03-05 11:05:59 -08001744
1745 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1746 return;
1747 }
1748
1749 nsecs_t currentTime = systemTime();
1750 if (mHasPoweredOff) {
1751 mHasPoweredOff = false;
1752 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001753 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001754 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001755 if (numPeriods < NUM_BUCKETS - 1) {
1756 mFrameBuckets[numPeriods] += elapsedTime;
1757 } else {
1758 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1759 }
1760 mTotalTime += elapsedTime;
1761 }
1762 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001763}
1764
1765void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001766 ATRACE_CALL();
1767 ALOGV("rebuildLayerStacks");
1768
Mathias Agopiancd60f992012-08-16 16:28:27 -07001769 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001770 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001771 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001772 mVisibleRegionsDirty = false;
1773 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001774
Jeff Sharkey76488112017-02-27 14:15:18 -07001775 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1776 Region opaqueRegion;
1777 Region dirtyRegion;
1778 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001779 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001780 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1781 const Transform& tr(displayDevice->getTransform());
1782 const Rect bounds(displayDevice->getBounds());
1783 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001784 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001785
Jeff Sharkey76488112017-02-27 14:15:18 -07001786 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001787 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001788 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1789 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001790 Region drawRegion(tr.transform(
1791 layer->visibleNonTransparentRegion));
1792 drawRegion.andSelf(bounds);
1793 if (!drawRegion.isEmpty()) {
1794 layersSortedByZ.add(layer);
1795 } else {
1796 // Clear out the HWC layer if this layer was
1797 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001798 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001799 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001800 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001801 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001802 // WM changes displayDevice->layerStack upon sleep/awake.
1803 // Here we make sure we delete the HWC layers even if
1804 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001805 hwcLayerDestroyed = layer->destroyHwcLayer(
1806 displayDevice->getHwcDisplayId());
1807 }
1808
1809 // If a layer is not going to get a release fence because
1810 // it is invisible, but it is also going to release its
1811 // old buffer, add it to the list of layers needing
1812 // fences.
1813 if (hwcLayerDestroyed) {
1814 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1815 mLayersWithQueuedFrames.cend(), layer);
1816 if (found != mLayersWithQueuedFrames.cend()) {
1817 layersNeedingFences.add(layer);
1818 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001819 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001820 });
1821 }
1822 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001823 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001824 displayDevice->undefinedRegion.set(bounds);
1825 displayDevice->undefinedRegion.subtractSelf(
1826 tr.transform(opaqueRegion));
1827 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001828 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001829 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001830}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001831
Romain Guy0147a172017-06-01 13:53:56 -07001832mat4 SurfaceFlinger::computeSaturationMatrix() const {
1833 if (mSaturation == 1.0f) {
1834 return mat4();
1835 }
1836
1837 // Rec.709 luma coefficients
1838 float3 luminance{0.213f, 0.715f, 0.072f};
1839 luminance *= 1.0f - mSaturation;
1840 return mat4(
1841 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1842 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1843 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1844 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1845 );
1846}
1847
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001848// pickColorMode translates a given dataspace into the best available color mode.
1849// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001850android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001851 if (mForceNativeColorMode) {
1852 return HAL_COLOR_MODE_NATIVE;
1853 }
1854
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001855 switch (dataSpace) {
1856 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1857 // system expects.
1858 case HAL_DATASPACE_UNKNOWN:
1859 case HAL_DATASPACE_SRGB:
1860 case HAL_DATASPACE_V0_SRGB:
1861 return HAL_COLOR_MODE_SRGB;
1862 break;
1863
1864 case HAL_DATASPACE_DISPLAY_P3:
1865 return HAL_COLOR_MODE_DISPLAY_P3;
1866 break;
1867
1868 default:
1869 // TODO (courtneygo): Do we want to assert an error here?
1870 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1871 dataSpace);
1872 return HAL_COLOR_MODE_SRGB;
1873 break;
1874 }
1875}
1876
Romain Guy0147a172017-06-01 13:53:56 -07001877android_dataspace SurfaceFlinger::bestTargetDataSpace(
1878 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001879 // Only support sRGB and Display-P3 right now.
1880 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1881 return HAL_DATASPACE_DISPLAY_P3;
1882 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001883 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1884 return HAL_DATASPACE_DISPLAY_P3;
1885 }
1886 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1887 return HAL_DATASPACE_DISPLAY_P3;
1888 }
1889
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001890 return HAL_DATASPACE_V0_SRGB;
1891}
1892
Mathias Agopiancd60f992012-08-16 16:28:27 -07001893void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001894 ATRACE_CALL();
1895 ALOGV("setUpHWComposer");
1896
Jesse Hall028dc8f2013-08-20 16:35:32 -07001897 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001898 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1899 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1900 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1901
1902 // If nothing has changed (!dirty), don't recompose.
1903 // If something changed, but we don't currently have any visible layers,
1904 // and didn't when we last did a composition, then skip it this time.
1905 // The second rule does two things:
1906 // - When all layers are removed from a display, we'll emit one black
1907 // frame, then nothing more until we get new layers.
1908 // - When a display is created with a private layer stack, we won't
1909 // emit any black frames until a layer is added to the layer stack.
1910 bool mustRecompose = dirty && !(empty && wasEmpty);
1911
1912 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1913 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1914 mustRecompose ? "doing" : "skipping",
1915 dirty ? "+" : "-",
1916 empty ? "+" : "-",
1917 wasEmpty ? "+" : "-");
1918
Dan Stoza71433162014-02-04 16:22:36 -08001919 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001920
1921 if (mustRecompose) {
1922 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1923 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001924 }
1925
Dan Stoza9e56aa02015-11-02 13:00:03 -08001926 // build the h/w work list
1927 if (CC_UNLIKELY(mGeometryInvalid)) {
1928 mGeometryInvalid = false;
1929 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1930 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1931 const auto hwcId = displayDevice->getHwcDisplayId();
1932 if (hwcId >= 0) {
1933 const Vector<sp<Layer>>& currentLayers(
1934 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001935 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001936 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001937 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001938 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001941 }
1942 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001943
Robert Carrae060832016-11-28 10:51:00 -08001944 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001945 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001947 }
1948 }
1949 }
1950 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951 }
Riley Andrews03414a12014-07-01 14:22:59 -07001952
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001953
Romain Guy0147a172017-06-01 13:53:56 -07001954 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001955
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 // Set the per-frame data
1957 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1958 auto& displayDevice = mDisplays[displayId];
1959 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001960
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 if (hwcId < 0) {
1962 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001963 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001964 if (colorMatrix != mPreviousColorMatrix) {
1965 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1966 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1967 "display %zd: %d", displayId, result);
1968 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001969 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
chaviwc9232ed2017-11-14 15:31:15 -08001970 if (layer->getForceClientComposition(hwcId)) {
1971 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1972 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1973 continue;
1974 }
1975
Dan Stoza9e56aa02015-11-02 13:00:03 -08001976 layer->setPerFrameData(displayDevice);
1977 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001978
1979 if (hasWideColorDisplay) {
1980 android_color_mode newColorMode;
1981 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1982
1983 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1984 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1985 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1986 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1987 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1988 }
1989 newColorMode = pickColorMode(newDataSpace);
1990
Thierry Strudel2924d012017-08-14 15:19:37 -07001991 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001992 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001993 }
1994
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001995 mPreviousColorMatrix = colorMatrix;
1996
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001998 auto& displayDevice = mDisplays[displayId];
1999 if (!displayDevice->isDisplayOn()) {
2000 continue;
2001 }
2002
2003 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2005 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002006 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002008
Mathias Agopiancd60f992012-08-16 16:28:27 -07002009void SurfaceFlinger::doComposition() {
2010 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002011 ALOGV("doComposition");
2012
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002013 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002014 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002015 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002016 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002017 // transform the dirty region into this screen's coordinate space
2018 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002019
2020 // repaint the framebuffer (if needed)
2021 doDisplayComposition(hw, dirtyRegion);
2022
Mathias Agopiancd60f992012-08-16 16:28:27 -07002023 hw->dirtyRegion.clear();
2024 hw->flip(hw->swapRegion);
2025 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07002026 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002027 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002028 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002029}
2030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002031void SurfaceFlinger::postFramebuffer()
2032{
Mathias Agopian841cde52012-03-01 15:44:37 -08002033 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002035
Mathias Agopiana44b0412011-10-16 18:46:35 -07002036 const nsecs_t now = systemTime();
2037 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002038
Dan Stoza9e56aa02015-11-02 13:00:03 -08002039 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2040 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002041 if (!displayDevice->isDisplayOn()) {
2042 continue;
2043 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002044 const auto hwcId = displayDevice->getHwcDisplayId();
2045 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002046 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002047 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002048 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002049 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002051 // The layer buffer from the previous frame (if any) is released
2052 // by HWC only when the release fence from this frame (if any) is
2053 // signaled. Always get the release fence from HWC first.
2054 auto hwcLayer = layer->getHwcLayer(hwcId);
2055 sp<Fence> releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2056
2057 // If the layer was client composited in the previous frame, we
2058 // need to merge with the previous client target acquire fence.
2059 // Since we do not track that, always merge with the current
2060 // client target acquire fence when it is available, even though
2061 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002062 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002063 releaseFence = Fence::merge("LayerRelease", releaseFence,
2064 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002065 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002066
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 layer->onLayerDisplayed(releaseFence);
2068 }
Chia-I Wu83806892017-11-16 10:50:20 -08002069
2070 // We've got a list of layers needing fences, that are disjoint with
2071 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2072 // supply them with the present fence.
2073 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
2074 sp<Fence> presentFence = mHwc->getPresentFence(hwcId);
2075 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2076 layer->onLayerDisplayed(presentFence);
2077 }
2078 }
2079
Dan Stoza9e56aa02015-11-02 13:00:03 -08002080 if (hwcId >= 0) {
2081 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002082 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002083 }
2084
Mathias Agopiana44b0412011-10-16 18:46:35 -07002085 mLastSwapBufferTime = systemTime() - now;
2086 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002087
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002088 // |mStateLock| not needed as we are on the main thread
2089 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002090 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2091 logFrameStats();
2092 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093}
2094
Mathias Agopian87baae12012-07-31 12:38:26 -07002095void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002096{
Mathias Agopian841cde52012-03-01 15:44:37 -08002097 ATRACE_CALL();
2098
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002099 // here we keep a copy of the drawing state (that is the state that's
2100 // going to be overwritten by handleTransactionLocked()) outside of
2101 // mStateLock so that the side-effects of the State assignment
2102 // don't happen with mStateLock held (which can cause deadlocks).
2103 State drawingState(mDrawingState);
2104
Mathias Agopianca4d3602011-05-19 15:38:14 -07002105 Mutex::Autolock _l(mStateLock);
2106 const nsecs_t now = systemTime();
2107 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002108
Mathias Agopianca4d3602011-05-19 15:38:14 -07002109 // Here we're guaranteed that some transaction flags are set
2110 // so we can call handleTransactionLocked() unconditionally.
2111 // We call getTransactionFlags(), which will also clear the flags,
2112 // with mStateLock held to guarantee that mCurrentState won't change
2113 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002114
Mathias Agopiane57f2922012-08-09 16:29:12 -07002115 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002116 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002117
Mathias Agopianca4d3602011-05-19 15:38:14 -07002118 mLastTransactionTime = systemTime() - now;
2119 mDebugInTransaction = 0;
2120 invalidateHwcGeometry();
2121 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002122}
2123
Mathias Agopian87baae12012-07-31 12:38:26 -07002124void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002125{
Dan Stoza7dde5992015-05-22 09:51:44 -07002126 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002127 mCurrentState.traverseInZOrder([](Layer* layer) {
2128 layer->notifyAvailableFrames();
2129 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131 /*
2132 * Traversal of the children
2133 * (perform the transaction for each of them if needed)
2134 */
2135
Mathias Agopian3559b072012-08-15 13:46:03 -07002136 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002137 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002139 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002140
2141 const uint32_t flags = layer->doTransaction(0);
2142 if (flags & Layer::eVisibleRegion)
2143 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002144 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002145 }
2146
2147 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002148 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149 */
2150
Mathias Agopiane57f2922012-08-09 16:29:12 -07002151 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002152 // here we take advantage of Vector's copy-on-write semantics to
2153 // improve performance by skipping the transaction entirely when
2154 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002155 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2156 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002157 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002158 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002159 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002160 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002161
2162 // find the displays that were removed
2163 // (ie: in drawing state but not in current state)
2164 // also handle displays that changed
2165 // (ie: displays that are in both lists)
2166 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002167 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2168 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002169 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002170 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002171 // Call makeCurrent() on the primary display so we can
2172 // be sure that nothing associated with this display
2173 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002174 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002175 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002176 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002177 if (hw != NULL)
2178 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002179 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002180 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002181 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002182 } else {
2183 ALOGW("trying to remove the main display");
2184 }
2185 } else {
2186 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002187 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002188 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002189 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2190 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002191 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002192 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002193 // recreating the DisplayDevice, so we just remove it
2194 // from the drawing state, so that it get re-added
2195 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002196 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002197 if (hw != NULL)
2198 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002199 mDisplays.removeItem(display);
2200 mDrawingState.displays.removeItemsAt(i);
2201 dc--; i--;
2202 // at this point we must loop to the next item
2203 continue;
2204 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002205
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002206 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002207 if (disp != NULL) {
2208 if (state.layerStack != draw[i].layerStack) {
2209 disp->setLayerStack(state.layerStack);
2210 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002211 if ((state.orientation != draw[i].orientation)
2212 || (state.viewport != draw[i].viewport)
2213 || (state.frame != draw[i].frame))
2214 {
2215 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002216 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002217 }
Michael Lentine47e45402014-07-18 15:34:25 -07002218 if (state.width != draw[i].width || state.height != draw[i].height) {
2219 disp->setDisplaySize(state.width, state.height);
2220 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002221 }
2222 }
2223 }
2224
2225 // find displays that were added
2226 // (ie: in current state but not in drawing state)
2227 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002228 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002229 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002230
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002231 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002232 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002233 sp<IGraphicBufferProducer> bqProducer;
2234 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002235 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002236
Dan Stoza9e56aa02015-11-02 13:00:03 -08002237 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002238 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002239 // Virtual displays without a surface are dormant:
2240 // they have external state (layer stack, projection,
2241 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002242 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002243
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002244 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002245 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002246 int width = 0;
2247 int status = state.surface->query(
2248 NATIVE_WINDOW_WIDTH, &width);
2249 ALOGE_IF(status != NO_ERROR,
2250 "Unable to query width (%d)", status);
2251 int height = 0;
2252 status = state.surface->query(
2253 NATIVE_WINDOW_HEIGHT, &height);
2254 ALOGE_IF(status != NO_ERROR,
2255 "Unable to query height (%d)", status);
2256 int intFormat = 0;
2257 status = state.surface->query(
2258 NATIVE_WINDOW_FORMAT, &intFormat);
2259 ALOGE_IF(status != NO_ERROR,
2260 "Unable to query format (%d)", status);
2261 auto format = static_cast<android_pixel_format_t>(
2262 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002263
Dan Stoza8cf150a2016-08-02 10:27:31 -07002264 mHwc->allocateVirtualDisplay(width, height, &format,
2265 &hwcId);
2266 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002267
Dan Stoza5cf424b2016-05-20 14:02:39 -07002268 // TODO: Plumb requested format back up to consumer
2269
Dan Stoza9e56aa02015-11-02 13:00:03 -08002270 sp<VirtualDisplaySurface> vds =
2271 new VirtualDisplaySurface(*mHwc,
2272 hwcId, state.surface, bqProducer,
2273 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002274
2275 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002276 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002277 }
2278 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002279 ALOGE_IF(state.surface!=NULL,
2280 "adding a supported display, but rendering "
2281 "surface is provided (%p), ignoring it",
2282 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002283
2284 hwcId = state.type;
2285 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2286 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002287 }
2288
2289 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002290 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002291 sp<DisplayDevice> hw =
2292 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2293 dispSurface, producer,
2294 mRenderEngine->getEGLConfig(),
2295 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002296 hw->setLayerStack(state.layerStack);
2297 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002298 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002299 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002300 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002301 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002302 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002303 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002304 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002305 }
2306 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002307 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002308 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309
Mathias Agopian84300952012-11-21 16:02:13 -08002310 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2311 // The transform hint might have changed for some layers
2312 // (either because a display has changed, or because a layer
2313 // as changed).
2314 //
2315 // Walk through all the layers in currentLayers,
2316 // and update their transform hint.
2317 //
2318 // If a layer is visible only on a single display, then that
2319 // display is used to calculate the hint, otherwise we use the
2320 // default display.
2321 //
2322 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2323 // the hint is set before we acquire a buffer from the surface texture.
2324 //
2325 // NOTE: layer transactions have taken place already, so we use their
2326 // drawing state. However, SurfaceFlinger's own transaction has not
2327 // happened yet, so we must use the current state layer list
2328 // (soon to become the drawing state list).
2329 //
2330 sp<const DisplayDevice> disp;
2331 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002332 bool first = true;
2333 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002334 // NOTE: we rely on the fact that layers are sorted by
2335 // layerStack first (so we don't have to traverse the list
2336 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002337 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002338 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002339 currentlayerStack = layerStack;
2340 // figure out if this layerstack is mirrored
2341 // (more than one display) if so, pick the default display,
2342 // if not, pick the only display it's on.
2343 disp.clear();
2344 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2345 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002346 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002347 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002348 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002349 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002350 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002351 break;
2352 }
2353 }
2354 }
2355 }
Chet Haase91d25932013-04-11 15:24:55 -07002356 if (disp == NULL) {
2357 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2358 // redraw after transform hint changes. See bug 8508397.
2359
2360 // could be null when this layer is using a layerStack
2361 // that is not visible on any display. Also can occur at
2362 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002363 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002364 }
Chet Haase91d25932013-04-11 15:24:55 -07002365 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002366
2367 first = false;
2368 });
Mathias Agopian84300952012-11-21 16:02:13 -08002369 }
2370
2371
Mathias Agopian3559b072012-08-15 13:46:03 -07002372 /*
2373 * Perform our own transaction if needed
2374 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002375
2376 if (mLayersAdded) {
2377 mLayersAdded = false;
2378 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002379 mVisibleRegionsDirty = true;
2380 }
2381
2382 // some layers might have been removed, so
2383 // we need to update the regions they're exposing.
2384 if (mLayersRemoved) {
2385 mLayersRemoved = false;
2386 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002387 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002388 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002389 // this layer is not visible anymore
2390 // TODO: we could traverse the tree from front to back and
2391 // compute the actual visible region
2392 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002393 Region visibleReg;
2394 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002395 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002396 }
Robert Carr2047fae2016-11-28 14:09:09 -08002397 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002398 }
2399
2400 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002401
2402 updateCursorAsync();
2403}
2404
2405void SurfaceFlinger::updateCursorAsync()
2406{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002407 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2408 auto& displayDevice = mDisplays[displayId];
2409 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002410 continue;
2411 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002412
2413 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2414 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002415 }
2416 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002417}
2418
2419void SurfaceFlinger::commitTransaction()
2420{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002421 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002422 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002423 for (const auto& l : mLayersPendingRemoval) {
2424 recordBufferingStats(l->getName().string(),
2425 l->getOccupancyHistory(true));
2426 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002427 }
2428 mLayersPendingRemoval.clear();
2429 }
2430
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002431 // If this transaction is part of a window animation then the next frame
2432 // we composite should be considered an animation as well.
2433 mAnimCompositionPending = mAnimTransactionPending;
2434
Mathias Agopian4fec8732012-06-29 14:12:52 -07002435 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002436 mDrawingState.traverseInZOrder([](Layer* layer) {
2437 layer->commitChildList();
2438 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002439 mTransactionPending = false;
2440 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002441 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002442}
2443
Chia-I Wuab0c3192017-08-01 11:29:00 -07002444void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002445 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002446{
Mathias Agopian841cde52012-03-01 15:44:37 -08002447 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002448 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002449
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450 Region aboveOpaqueLayers;
2451 Region aboveCoveredLayers;
2452 Region dirty;
2453
Mathias Agopian87baae12012-07-31 12:38:26 -07002454 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455
Robert Carr2047fae2016-11-28 14:09:09 -08002456 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002458 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002459
Jesse Hall01e29052013-02-19 16:13:35 -08002460 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002461 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002462 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002463
Mathias Agopianab028732010-03-16 16:41:46 -07002464 /*
2465 * opaqueRegion: area of a surface that is fully opaque.
2466 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002468
2469 /*
2470 * visibleRegion: area of a surface that is visible on screen
2471 * and not fully transparent. This is essentially the layer's
2472 * footprint minus the opaque regions above it.
2473 * Areas covered by a translucent surface are considered visible.
2474 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002475 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002476
2477 /*
2478 * coveredRegion: area of a surface that is covered by all
2479 * visible regions above it (which includes the translucent areas).
2480 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002481 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002482
Jesse Halla8026d22012-09-25 13:25:04 -07002483 /*
2484 * transparentRegion: area of a surface that is hinted to be completely
2485 * transparent. This is only used to tell when the layer has no visible
2486 * non-transparent regions and can be removed from the layer list. It
2487 * does not affect the visibleRegion of this layer or any layers
2488 * beneath it. The hint may not be correct if apps don't respect the
2489 * SurfaceView restrictions (which, sadly, some don't).
2490 */
2491 Region transparentRegion;
2492
Mathias Agopianab028732010-03-16 16:41:46 -07002493
2494 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002495 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002496 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002497 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002499 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002500 if (!visibleRegion.isEmpty()) {
2501 // Remove the transparent area from the visible region
2502 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002503 if (tr.preserveRects()) {
2504 // transform the transparent region
2505 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002506 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002507 // transformation too complex, can't do the
2508 // transparent region optimization.
2509 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002510 }
Mathias Agopianab028732010-03-16 16:41:46 -07002511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512
Mathias Agopianab028732010-03-16 16:41:46 -07002513 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002514 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002515 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002516 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2517 // the opaque region is the layer's footprint
2518 opaqueRegion = visibleRegion;
2519 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520 }
2521 }
2522
Mathias Agopianab028732010-03-16 16:41:46 -07002523 // Clip the covered region to the visible region
2524 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2525
2526 // Update aboveCoveredLayers for next (lower) layer
2527 aboveCoveredLayers.orSelf(visibleRegion);
2528
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002529 // subtract the opaque region covered by the layers above us
2530 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002531
2532 // compute this layer's dirty region
2533 if (layer->contentDirty) {
2534 // we need to invalidate the whole region
2535 dirty = visibleRegion;
2536 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002537 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538 layer->contentDirty = false;
2539 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002540 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002541 * the exposed region consists of two components:
2542 * 1) what's VISIBLE now and was COVERED before
2543 * 2) what's EXPOSED now less what was EXPOSED before
2544 *
2545 * note that (1) is conservative, we start with the whole
2546 * visible region but only keep what used to be covered by
2547 * something -- which mean it may have been exposed.
2548 *
2549 * (2) handles areas that were not covered by anything but got
2550 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002551 */
Mathias Agopianab028732010-03-16 16:41:46 -07002552 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002553 const Region oldVisibleRegion = layer->visibleRegion;
2554 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002555 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2556 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557 }
2558 dirty.subtractSelf(aboveOpaqueLayers);
2559
2560 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002561 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562
Mathias Agopianab028732010-03-16 16:41:46 -07002563 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002565
Jesse Halla8026d22012-09-25 13:25:04 -07002566 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567 layer->setVisibleRegion(visibleRegion);
2568 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002569 layer->setVisibleNonTransparentRegion(
2570 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002571 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572
Mathias Agopian87baae12012-07-31 12:38:26 -07002573 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002574}
2575
Chia-I Wuab0c3192017-08-01 11:29:00 -07002576void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002577 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002578 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002579 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002580 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002581 }
2582 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002583}
2584
Dan Stoza6b9454d2014-11-07 16:00:59 -08002585bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002587 ALOGV("handlePageFlip");
2588
Brian Andersond6927fb2016-07-23 23:37:30 -07002589 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590
Mathias Agopian4fec8732012-06-29 14:12:52 -07002591 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002592 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002593 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002594
2595 // Store the set of layers that need updates. This set must not change as
2596 // buffers are being latched, as this could result in a deadlock.
2597 // Example: Two producers share the same command stream and:
2598 // 1.) Layer 0 is latched
2599 // 2.) Layer 0 gets a new frame
2600 // 2.) Layer 1 gets a new frame
2601 // 3.) Layer 1 is latched.
2602 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2603 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002604 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002605 if (layer->hasQueuedFrame()) {
2606 frameQueued = true;
2607 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002608 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002609 } else {
2610 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002611 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002612 } else {
2613 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002614 }
Robert Carr2047fae2016-11-28 14:09:09 -08002615 });
2616
Dan Stoza9e56aa02015-11-02 13:00:03 -08002617 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002618 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002619 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002620 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002621 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002622 newDataLatched = true;
2623 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002624 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002625
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002626 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002627
2628 // If we will need to wake up at some time in the future to deal with a
2629 // queued frame that shouldn't be displayed during this vsync period, wake
2630 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002631 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002632 signalLayerUpdate();
2633 }
2634
2635 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002636 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637}
2638
Mathias Agopianad456f92011-01-13 17:53:01 -08002639void SurfaceFlinger::invalidateHwcGeometry()
2640{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002641 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002642}
2643
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002644
Fabien Sanglard830b8472016-11-30 16:35:58 -08002645void SurfaceFlinger::doDisplayComposition(
2646 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002647 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648{
Dan Stoza71433162014-02-04 16:22:36 -08002649 // We only need to actually compose the display if:
2650 // 1) It is being handled by hardware composer, which may need this to
2651 // keep its virtual display state machine in sync, or
2652 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002653 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002654 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002655 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002656 return;
2657 }
2658
Dan Stoza9e56aa02015-11-02 13:00:03 -08002659 ALOGV("doDisplayComposition");
2660
Mathias Agopian87baae12012-07-31 12:38:26 -07002661 Region dirtyRegion(inDirtyRegion);
2662
Mathias Agopianb8a55602009-06-26 19:06:36 -07002663 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002664 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665
Fabien Sanglard830b8472016-11-30 16:35:58 -08002666 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002667 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002668 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2669 // takes a rectangle, we must make sure to update that whole
2670 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002671 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002672 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002673 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002674 // We need to redraw the rectangle that will be updated
2675 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002676 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002677 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002678 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002679 } else {
2680 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002681 dirtyRegion.set(displayDevice->bounds());
2682 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002683 }
2684 }
2685
Fabien Sanglard830b8472016-11-30 16:35:58 -08002686 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002688 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002689 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002690
2691 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002692 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002693}
2694
Dan Stoza9e56aa02015-11-02 13:00:03 -08002695bool SurfaceFlinger::doComposeSurfaces(
2696 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002697{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002698 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002699
chaviwa76b2712017-09-20 12:02:26 -07002700 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002701 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002702
2703 mat4 oldColorMatrix;
2704 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2705 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2706 if (applyColorMatrix) {
2707 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2708 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2709 }
2710
Dan Stoza9e56aa02015-11-02 13:00:03 -08002711 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2712 if (hasClientComposition) {
2713 ALOGV("hasClientComposition");
2714
Romain Guy54f154a2017-10-24 21:40:32 +01002715 mRenderEngine->setWideColor(
2716 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2717 mRenderEngine->setColorMode(mForceNativeColorMode ?
2718 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002719 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002720 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002721 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002722 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002723
2724 // |mStateLock| not needed as we are on the main thread
2725 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002726 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2727 }
2728 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002729 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002730
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002731 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002732 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2733 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002734 // when using overlays, we assume a fully transparent framebuffer
2735 // NOTE: we could reduce how much we need to clear, for instance
2736 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002737 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002738 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002739 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002740 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002741 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002742 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002743
2744 // we remove the scissor part
2745 // we're left with the letterbox region
2746 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002747 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002748
2749 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002750 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002751
2752 // but limit it to the dirty region
2753 region.andSelf(dirty);
2754
Mathias Agopianb9494d52012-04-18 02:28:45 -07002755 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002756 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002757 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002758 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002759 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002760 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002761
Dan Stoza9e56aa02015-11-02 13:00:03 -08002762 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002763 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002764 // scissor on the main display. It should never be needed
2765 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002766 const Rect& bounds(displayDevice->getBounds());
2767 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002768 if (scissor != bounds) {
2769 // scissor doesn't match the screen's dimensions, so we
2770 // need to clear everything outside of it and enable
2771 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002772
Mathias Agopianf45c5102012-10-24 16:29:17 -07002773 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002774 const uint32_t height = displayDevice->getHeight();
2775 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002776 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002777 }
2778 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002779 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002780
Mathias Agopian85d751c2012-08-29 16:59:24 -07002781 /*
2782 * and then, render the layers targeted at the framebuffer
2783 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002784
Dan Stoza9e56aa02015-11-02 13:00:03 -08002785 ALOGV("Rendering client layers");
2786 const Transform& displayTransform = displayDevice->getTransform();
2787 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002788 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002789 bool firstLayer = true;
2790 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2791 const Region clip(dirty.intersect(
2792 displayTransform.transform(layer->visibleRegion)));
2793 ALOGV("Layer: %s", layer->getName().string());
2794 ALOGV(" Composition type: %s",
2795 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002796 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002797 switch (layer->getCompositionType(hwcId)) {
2798 case HWC2::Composition::Cursor:
2799 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002800 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002801 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002802 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002803 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002804 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002805 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002806 // never clear the very first layer since we're
2807 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002808 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002809 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002810 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002811 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002812 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002813 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002814 break;
2815 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002816 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002817 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002818 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002819 } else {
2820 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002821 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002822 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002823 }
2824 } else {
2825 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002826 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002827 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002828 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002829 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002830 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002831 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002832 }
2833 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002834
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002835 if (applyColorMatrix) {
2836 getRenderEngine().setupColorTransform(oldColorMatrix);
2837 }
2838
Mathias Agopianf45c5102012-10-24 16:29:17 -07002839 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002840 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002841 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842}
2843
Fabien Sanglard830b8472016-11-30 16:35:58 -08002844void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2845 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002846 RenderEngine& engine(getRenderEngine());
2847 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848}
2849
Dan Stoza7d89d062015-04-30 13:29:25 -07002850status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002851 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002852 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002853 const sp<Layer>& lbc,
2854 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002855{
Dan Stoza7d89d062015-04-30 13:29:25 -07002856 // add this layer to the current state list
2857 {
2858 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002859 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002860 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2861 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002862 return NO_MEMORY;
2863 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002864 if (parent == nullptr) {
2865 mCurrentState.layersSortedByZ.add(lbc);
2866 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002867 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002868 ALOGE("addClientLayer called with a removed parent");
2869 return NAME_NOT_FOUND;
2870 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002871 parent->addChild(lbc);
2872 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002873
Dan Stoza7d89d062015-04-30 13:29:25 -07002874 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002875 mLayersAdded = true;
2876 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002877 }
2878
Mathias Agopian96f08192010-06-02 23:28:45 -07002879 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002880 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002881
Dan Stoza7d89d062015-04-30 13:29:25 -07002882 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002883}
2884
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002885status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002886 Mutex::Autolock _l(mStateLock);
2887
chaviw8b3871a2017-11-01 17:41:01 -07002888 if (layer->isPendingRemoval()) {
2889 return NO_ERROR;
2890 }
2891
Robert Carr1f0a16a2016-10-24 16:27:39 -07002892 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002893 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002894 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002895 if (topLevelOnly) {
2896 return NO_ERROR;
2897 }
2898
Chia-I Wu98f1c102017-05-30 14:54:08 -07002899 sp<Layer> ancestor = p;
2900 while (ancestor->getParent() != nullptr) {
2901 ancestor = ancestor->getParent();
2902 }
2903 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2904 ALOGE("removeLayer called with a layer whose parent has been removed");
2905 return NAME_NOT_FOUND;
2906 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002907
2908 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002909 } else {
2910 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002911 }
2912
Robert Carr136e2f62017-02-08 17:54:29 -08002913 // As a matter of normal operation, the LayerCleaner will produce a second
2914 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2915 // so we will succeed in promoting it, but it's already been removed
2916 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2917 // otherwise something has gone wrong and we are leaking the layer.
2918 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002919 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2920 layer->getName().string(),
2921 (p != nullptr) ? p->getName().string() : "no-parent");
2922 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002923 } else if (index < 0) {
2924 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002925 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002926
Chia-I Wuc6657022017-08-15 11:18:17 -07002927 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002928 mLayersPendingRemoval.add(layer);
2929 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002930 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002931 setTransactionFlags(eTransactionNeeded);
2932 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002933}
2934
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002935uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002936 return android_atomic_release_load(&mTransactionFlags);
2937}
2938
Mathias Agopian3f844832013-08-07 21:24:32 -07002939uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002940 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2941}
2942
Mathias Agopian3f844832013-08-07 21:24:32 -07002943uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002944 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2945 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002946 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002947 }
2948 return old;
2949}
2950
Mathias Agopian8b33f032012-07-24 20:43:54 -07002951void SurfaceFlinger::setTransactionState(
2952 const Vector<ComposerState>& state,
2953 const Vector<DisplayState>& displays,
2954 uint32_t flags)
2955{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002956 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002957 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002958 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002959
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002960 if (flags & eAnimation) {
2961 // For window updates that are part of an animation we must wait for
2962 // previous animation "frames" to be handled.
2963 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002964 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002965 if (CC_UNLIKELY(err != NO_ERROR)) {
2966 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002967 // caller after a few seconds.
2968 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2969 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002970 mAnimTransactionPending = false;
2971 break;
2972 }
2973 }
2974 }
2975
Mathias Agopiane57f2922012-08-09 16:29:12 -07002976 size_t count = displays.size();
2977 for (size_t i=0 ; i<count ; i++) {
2978 const DisplayState& s(displays[i]);
2979 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002980 }
2981
Mathias Agopiane57f2922012-08-09 16:29:12 -07002982 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002983 for (size_t i=0 ; i<count ; i++) {
2984 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002985 // Here we need to check that the interface we're given is indeed
2986 // one of our own. A malicious client could give us a NULL
2987 // IInterface, or one of its own or even one of our own but a
2988 // different type. All these situations would cause us to crash.
2989 //
2990 // NOTE: it would be better to use RTTI as we could directly check
2991 // that we have a Client*. however, RTTI is disabled in Android.
2992 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002993 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002994 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002995 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002996 sp<Client> client( static_cast<Client *>(s.client.get()) );
2997 transactionFlags |= setClientStateLocked(client, s.state);
2998 }
2999 }
3000 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003001 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003002
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003003 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3004 // anyway. This can be used as a flush mechanism for previous async transactions.
3005 // Empty animation transaction can be used to simulate back-pressure, so also force a
3006 // transaction for empty animation transactions.
3007 if (transactionFlags == 0 &&
3008 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003009 transactionFlags = eTransactionNeeded;
3010 }
3011
Mathias Agopian386aa982011-11-07 21:58:03 -08003012 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003013 if (mInterceptor.isEnabled()) {
3014 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
3015 }
Irvel468051e2016-06-13 16:44:44 -07003016
Mathias Agopian386aa982011-11-07 21:58:03 -08003017 // this triggers the transaction
3018 setTransactionFlags(transactionFlags);
3019
3020 // if this is a synchronous transaction, wait for it to take effect
3021 // before returning.
3022 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003023 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003024 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003025 if (flags & eAnimation) {
3026 mAnimTransactionPending = true;
3027 }
3028 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003029 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3030 if (CC_UNLIKELY(err != NO_ERROR)) {
3031 // just in case something goes wrong in SF, return to the
3032 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003033 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3034 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003035 break;
3036 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003037 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003038 }
3039}
3040
Mathias Agopiane57f2922012-08-09 16:29:12 -07003041uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3042{
Jesse Hall9a143922012-10-04 16:29:19 -07003043 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3044 if (dpyIdx < 0)
3045 return 0;
3046
Mathias Agopiane57f2922012-08-09 16:29:12 -07003047 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003048 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003049 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003050 const uint32_t what = s.what;
3051 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003052 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003053 disp.surface = s.surface;
3054 flags |= eDisplayTransactionNeeded;
3055 }
3056 }
3057 if (what & DisplayState::eLayerStackChanged) {
3058 if (disp.layerStack != s.layerStack) {
3059 disp.layerStack = s.layerStack;
3060 flags |= eDisplayTransactionNeeded;
3061 }
3062 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003063 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003064 if (disp.orientation != s.orientation) {
3065 disp.orientation = s.orientation;
3066 flags |= eDisplayTransactionNeeded;
3067 }
3068 if (disp.frame != s.frame) {
3069 disp.frame = s.frame;
3070 flags |= eDisplayTransactionNeeded;
3071 }
3072 if (disp.viewport != s.viewport) {
3073 disp.viewport = s.viewport;
3074 flags |= eDisplayTransactionNeeded;
3075 }
3076 }
Michael Lentine47e45402014-07-18 15:34:25 -07003077 if (what & DisplayState::eDisplaySizeChanged) {
3078 if (disp.width != s.width) {
3079 disp.width = s.width;
3080 flags |= eDisplayTransactionNeeded;
3081 }
3082 if (disp.height != s.height) {
3083 disp.height = s.height;
3084 flags |= eDisplayTransactionNeeded;
3085 }
3086 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003087 }
3088 return flags;
3089}
3090
3091uint32_t SurfaceFlinger::setClientStateLocked(
3092 const sp<Client>& client,
3093 const layer_state_t& s)
3094{
Mathias Agopian13127d82013-03-05 17:47:11 -08003095 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003096 if (layer == nullptr) {
3097 return 0;
3098 }
3099
3100 if (layer->isPendingRemoval()) {
3101 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3102 return 0;
3103 }
3104
3105 uint32_t flags = 0;
3106
3107 const uint32_t what = s.what;
3108 bool geometryAppliesWithResize =
3109 what & layer_state_t::eGeometryAppliesWithResize;
3110 if (what & layer_state_t::ePositionChanged) {
3111 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3112 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003113 }
chaviw8b3871a2017-11-01 17:41:01 -07003114 }
3115 if (what & layer_state_t::eLayerChanged) {
3116 // NOTE: index needs to be calculated before we update the state
3117 const auto& p = layer->getParent();
3118 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003119 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003120 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003121 mCurrentState.layersSortedByZ.removeAt(idx);
3122 mCurrentState.layersSortedByZ.add(layer);
3123 // we need traversal (state changed)
3124 // AND transaction (list changed)
3125 flags |= eTransactionNeeded|eTraversalNeeded;
3126 }
chaviw8b3871a2017-11-01 17:41:01 -07003127 } else {
3128 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003129 flags |= eTransactionNeeded|eTraversalNeeded;
3130 }
3131 }
chaviw8b3871a2017-11-01 17:41:01 -07003132 }
3133 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003134 // NOTE: index needs to be calculated before we update the state
3135 const auto& p = layer->getParent();
3136 if (p == nullptr) {
3137 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3138 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3139 mCurrentState.layersSortedByZ.removeAt(idx);
3140 mCurrentState.layersSortedByZ.add(layer);
3141 // we need traversal (state changed)
3142 // AND transaction (list changed)
3143 flags |= eTransactionNeeded|eTraversalNeeded;
3144 }
3145 } else {
3146 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3147 flags |= eTransactionNeeded|eTraversalNeeded;
3148 }
chaviw8b3871a2017-11-01 17:41:01 -07003149 }
3150 }
3151 if (what & layer_state_t::eSizeChanged) {
3152 if (layer->setSize(s.w, s.h)) {
3153 flags |= eTraversalNeeded;
3154 }
3155 }
3156 if (what & layer_state_t::eAlphaChanged) {
3157 if (layer->setAlpha(s.alpha))
3158 flags |= eTraversalNeeded;
3159 }
3160 if (what & layer_state_t::eColorChanged) {
3161 if (layer->setColor(s.color))
3162 flags |= eTraversalNeeded;
3163 }
3164 if (what & layer_state_t::eMatrixChanged) {
3165 if (layer->setMatrix(s.matrix))
3166 flags |= eTraversalNeeded;
3167 }
3168 if (what & layer_state_t::eTransparentRegionChanged) {
3169 if (layer->setTransparentRegionHint(s.transparentRegion))
3170 flags |= eTraversalNeeded;
3171 }
3172 if (what & layer_state_t::eFlagsChanged) {
3173 if (layer->setFlags(s.flags, s.mask))
3174 flags |= eTraversalNeeded;
3175 }
3176 if (what & layer_state_t::eCropChanged) {
3177 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3178 flags |= eTraversalNeeded;
3179 }
3180 if (what & layer_state_t::eFinalCropChanged) {
3181 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3182 flags |= eTraversalNeeded;
3183 }
3184 if (what & layer_state_t::eLayerStackChanged) {
3185 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3186 // We only allow setting layer stacks for top level layers,
3187 // everything else inherits layer stack from its parent.
3188 if (layer->hasParent()) {
3189 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3190 layer->getName().string());
3191 } else if (idx < 0) {
3192 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3193 "that also does not appear in the top level layer list. Something"
3194 " has gone wrong.", layer->getName().string());
3195 } else if (layer->setLayerStack(s.layerStack)) {
3196 mCurrentState.layersSortedByZ.removeAt(idx);
3197 mCurrentState.layersSortedByZ.add(layer);
3198 // we need traversal (state changed)
3199 // AND transaction (list changed)
3200 flags |= eTransactionNeeded|eTraversalNeeded;
3201 }
3202 }
3203 if (what & layer_state_t::eDeferTransaction) {
3204 if (s.barrierHandle != nullptr) {
3205 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3206 } else if (s.barrierGbp != nullptr) {
3207 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3208 if (authenticateSurfaceTextureLocked(gbp)) {
3209 const auto& otherLayer =
3210 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3211 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3212 } else {
3213 ALOGE("Attempt to defer transaction to to an"
3214 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003215 }
3216 }
chaviw8b3871a2017-11-01 17:41:01 -07003217 // We don't trigger a traversal here because if no other state is
3218 // changed, we don't want this to cause any more work
3219 }
3220 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003221 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003222 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003223 if (!hadParent) {
3224 mCurrentState.layersSortedByZ.remove(layer);
3225 }
chaviw8b3871a2017-11-01 17:41:01 -07003226 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003227 }
chaviw8b3871a2017-11-01 17:41:01 -07003228 }
3229 if (what & layer_state_t::eReparentChildren) {
3230 if (layer->reparentChildren(s.reparentHandle)) {
3231 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003232 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003233 }
chaviw8b3871a2017-11-01 17:41:01 -07003234 if (what & layer_state_t::eDetachChildren) {
3235 layer->detachChildren();
3236 }
3237 if (what & layer_state_t::eOverrideScalingModeChanged) {
3238 layer->setOverrideScalingMode(s.overrideScalingMode);
3239 // We don't trigger a traversal here because if no other state is
3240 // changed, we don't want this to cause any more work
3241 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003242 return flags;
3243}
3244
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003245status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003246 const String8& name,
3247 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003248 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003249 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3250 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003251{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003252 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003253 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003254 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003255 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003256 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003257
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003258 status_t result = NO_ERROR;
3259
3260 sp<Layer> layer;
3261
Cody Northropbc755282017-03-31 12:00:08 -06003262 String8 uniqueName = getUniqueLayerName(name);
3263
Mathias Agopian3165cc22012-08-08 19:42:09 -07003264 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3265 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003266 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003267 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003268 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003269
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003270 break;
chaviw13fdc492017-06-27 12:40:18 -07003271 case ISurfaceComposerClient::eFXSurfaceColor:
3272 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003273 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003274 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003275 break;
3276 default:
3277 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278 break;
3279 }
3280
Dan Stoza7d89d062015-04-30 13:29:25 -07003281 if (result != NO_ERROR) {
3282 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003284
Chia-I Wuab0c3192017-08-01 11:29:00 -07003285 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3286 // TODO b/64227542
3287 if (windowType == 441731) {
3288 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3289 layer->setPrimaryDisplayOnly();
3290 }
3291
Albert Chaulk479c60c2017-01-27 14:21:34 -05003292 layer->setInfo(windowType, ownerUid);
3293
Robert Carr1f0a16a2016-10-24 16:27:39 -07003294 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003295 if (result != NO_ERROR) {
3296 return result;
3297 }
Irvelffc9efc2016-07-27 15:16:37 -07003298 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003299
3300 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003301 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003302}
3303
Cody Northropbc755282017-03-31 12:00:08 -06003304String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3305{
3306 bool matchFound = true;
3307 uint32_t dupeCounter = 0;
3308
3309 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3310 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3311
3312 // Loop over layers until we're sure there is no matching name
3313 while (matchFound) {
3314 matchFound = false;
3315 mDrawingState.traverseInZOrder([&](Layer* layer) {
3316 if (layer->getName() == uniqueName) {
3317 matchFound = true;
3318 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3319 }
3320 });
3321 }
3322
3323 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3324
3325 return uniqueName;
3326}
3327
David Sodman0c69cad2017-08-21 12:12:51 -07003328status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003329 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3330 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003331{
3332 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003333 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003334 case PIXEL_FORMAT_TRANSPARENT:
3335 case PIXEL_FORMAT_TRANSLUCENT:
3336 format = PIXEL_FORMAT_RGBA_8888;
3337 break;
3338 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003339 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003340 break;
3341 }
3342
David Sodman0c69cad2017-08-21 12:12:51 -07003343 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3344 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003345 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003346 *handle = layer->getHandle();
3347 *gbp = layer->getProducer();
3348 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003349 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003350
David Sodman0c69cad2017-08-21 12:12:51 -07003351 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003352 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353}
3354
chaviw13fdc492017-06-27 12:40:18 -07003355status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003356 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003357 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003358{
chaviw13fdc492017-06-27 12:40:18 -07003359 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003360 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003361 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003362}
3363
Mathias Agopianac9fa422013-02-11 16:40:36 -08003364status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003365{
Robert Carr9524cb32017-02-13 11:32:32 -08003366 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003367 status_t err = NO_ERROR;
3368 sp<Layer> l(client->getLayerUser(handle));
3369 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003370 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003371 err = removeLayer(l);
3372 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3373 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003374 }
3375 return err;
3376}
3377
Mathias Agopian13127d82013-03-05 17:47:11 -08003378status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003379{
Mathias Agopian67106042013-03-14 19:18:13 -07003380 // called by ~LayerCleaner() when all references to the IBinder (handle)
3381 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003382 sp<Layer> l = layer.promote();
3383 if (l == nullptr) {
3384 // The layer has already been removed, carry on
3385 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003386 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003387 // If we have a parent, then we can continue to live as long as it does.
3388 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003389}
3390
Mathias Agopianb60314a2012-04-10 22:09:54 -07003391// ---------------------------------------------------------------------------
3392
Andy McFadden13a082e2012-08-24 10:16:42 -07003393void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003394 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003395 Vector<ComposerState> state;
3396 Vector<DisplayState> displays;
3397 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003398 d.what = DisplayState::eDisplayProjectionChanged |
3399 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003400 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003401 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003402 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003403 d.frame.makeInvalid();
3404 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003405 d.width = 0;
3406 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003407 displays.add(d);
3408 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003409 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3410 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003411
Dan Stoza9e56aa02015-11-02 13:00:03 -08003412 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3413 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003414 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003415
Brian Andersond0010582017-03-07 13:20:31 -08003416 // Use phase of 0 since phase is not known.
3417 // Use latency of 0, which will snap to the ideal latency.
3418 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003419}
3420
3421void SurfaceFlinger::initializeDisplays() {
3422 class MessageScreenInitialized : public MessageBase {
3423 SurfaceFlinger* flinger;
3424 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003425 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003426 virtual bool handler() {
3427 flinger->onInitializeDisplays();
3428 return true;
3429 }
3430 };
3431 sp<MessageBase> msg = new MessageScreenInitialized(this);
3432 postMessageAsync(msg); // we may be called from main thread, use async message
3433}
3434
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003435void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003436 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003437 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3438 this);
3439 int32_t type = hw->getDisplayType();
3440 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003441
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003442 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003443 return;
3444 }
3445
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003446 hw->setPowerMode(mode);
3447 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3448 ALOGW("Trying to set power mode for virtual display");
3449 return;
3450 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003451
Irvelffc9efc2016-07-27 15:16:37 -07003452 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003453 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003454 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3455 if (idx < 0) {
3456 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3457 return;
3458 }
3459 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3460 }
3461
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003462 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003463 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003464 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003465 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3466 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003467 // FIXME: eventthread only knows about the main display right now
3468 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003469 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003470 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003471
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003472 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003473 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003474 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003475
3476 struct sched_param param = {0};
3477 param.sched_priority = 1;
3478 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3479 ALOGW("Couldn't set SCHED_FIFO on display on");
3480 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003481 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003482 // Turn off the display
3483 struct sched_param param = {0};
3484 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3485 ALOGW("Couldn't set SCHED_OTHER on display off");
3486 }
3487
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003488 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3489 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003490 disableHardwareVsync(true); // also cancels any in-progress resync
3491
Mathias Agopiancde87a32012-09-13 14:09:01 -07003492 // FIXME: eventthread only knows about the main display right now
3493 mEventThread->onScreenReleased();
3494 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003495
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003496 getHwComposer().setPowerMode(type, mode);
3497 mVisibleRegionsDirty = true;
3498 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003499 } else if (mode == HWC_POWER_MODE_DOZE ||
3500 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003501 // Update display while dozing
3502 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003503 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3504 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003505 // FIXME: eventthread only knows about the main display right now
3506 mEventThread->onScreenAcquired();
3507 resyncToHardwareVsync(true);
3508 }
3509 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3510 // Leave display going to doze
3511 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3512 disableHardwareVsync(true); // also cancels any in-progress resync
3513 // FIXME: eventthread only knows about the main display right now
3514 mEventThread->onScreenReleased();
3515 }
3516 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003517 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003518 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003519 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003520 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003521}
3522
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003523void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3524 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003525 SurfaceFlinger& mFlinger;
3526 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003527 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003528 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003529 MessageSetPowerMode(SurfaceFlinger& flinger,
3530 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3531 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003532 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003533 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003534 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003535 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003536 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003537 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003538 ALOGW("Attempt to set power mode = %d for virtual display",
3539 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003540 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003541 mFlinger.setPowerModeInternal(
3542 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003543 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003544 return true;
3545 }
3546 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003547 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003548 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003549}
3550
3551// ---------------------------------------------------------------------------
3552
Vishnu Nair6a408532017-10-24 09:11:27 -07003553status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003554 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003555
Mathias Agopianbd115332013-04-18 16:41:04 -07003556 IPCThreadState* ipc = IPCThreadState::self();
3557 const int pid = ipc->getCallingPid();
3558 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003559
Mathias Agopianbd115332013-04-18 16:41:04 -07003560 if ((uid != AID_SHELL) &&
3561 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003562 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003563 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003564 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003565 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003566 // (this would indicate SF is stuck, but we want to be able to
3567 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003568 status_t err = mStateLock.timedLock(s2ns(1));
3569 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003570 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003571 result.appendFormat(
3572 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3573 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003574 }
3575
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003576 bool dumpAll = true;
3577 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003578 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003579
3580 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003581 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003582 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3583 dumpAll = false;
3584 }
3585
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003586 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003587 if ((index < numArgs) &&
3588 (args[index] == String16("--list"))) {
3589 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003590 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003591 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003592 }
3593
3594 if ((index < numArgs) &&
3595 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003596 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003597 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003598 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003599 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003600
3601 if ((index < numArgs) &&
3602 (args[index] == String16("--latency-clear"))) {
3603 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003604 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003605 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003606 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003607
3608 if ((index < numArgs) &&
3609 (args[index] == String16("--dispsync"))) {
3610 index++;
3611 mPrimaryDispSync.dump(result);
3612 dumpAll = false;
3613 }
Dan Stozab90cf072015-03-05 11:05:59 -08003614
3615 if ((index < numArgs) &&
3616 (args[index] == String16("--static-screen"))) {
3617 index++;
3618 dumpStaticScreenStats(result);
3619 dumpAll = false;
3620 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003621
3622 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003623 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003624 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003625 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003626 dumpAll = false;
3627 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003628
3629 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3630 index++;
3631 dumpWideColorInfo(result);
3632 dumpAll = false;
3633 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003634 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003635
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003636 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003637 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003638 }
3639
Mathias Agopian9795c422009-08-26 16:36:26 -07003640 if (locked) {
3641 mStateLock.unlock();
3642 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643 }
3644 write(fd, result.string(), result.size());
3645 return NO_ERROR;
3646}
3647
Dan Stozac7014012014-02-14 15:03:43 -08003648void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3649 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003650{
Robert Carr2047fae2016-11-28 14:09:09 -08003651 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003652 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003653 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003654}
3655
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003656void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003657 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003658{
3659 String8 name;
3660 if (index < args.size()) {
3661 name = String8(args[index]);
3662 index++;
3663 }
3664
Dan Stoza9e56aa02015-11-02 13:00:03 -08003665 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3666 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003667 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003668
3669 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003670 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003671 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003672 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003673 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003674 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003675 }
Robert Carr2047fae2016-11-28 14:09:09 -08003676 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003677 }
3678}
3679
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003680void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003681 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003682{
3683 String8 name;
3684 if (index < args.size()) {
3685 name = String8(args[index]);
3686 index++;
3687 }
3688
Robert Carr2047fae2016-11-28 14:09:09 -08003689 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003690 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003691 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003692 }
Robert Carr2047fae2016-11-28 14:09:09 -08003693 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003694
Svetoslavd85084b2014-03-20 10:28:31 -07003695 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003696}
3697
Jamie Gennis6547ff42013-07-16 20:12:42 -07003698// This should only be called from the main thread. Otherwise it would need
3699// the lock and should use mCurrentState rather than mDrawingState.
3700void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003701 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003702 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003703 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003704
3705 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3706}
3707
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003708void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003709{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003710 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003711 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3712
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003713 if (isLayerTripleBufferingDisabled())
3714 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003715
3716 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003717 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003718 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003719 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003720 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3721 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003722 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003723}
3724
Dan Stozab90cf072015-03-05 11:05:59 -08003725void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3726{
3727 result.appendFormat("Static screen stats:\n");
3728 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3729 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3730 float percent = 100.0f *
3731 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3732 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3733 b + 1, bucketTimeSec, percent);
3734 }
3735 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3736 float percent = 100.0f *
3737 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3738 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3739 NUM_BUCKETS - 1, bucketTimeSec, percent);
3740}
3741
Dan Stozae77c7662016-05-13 11:37:28 -07003742void SurfaceFlinger::recordBufferingStats(const char* layerName,
3743 std::vector<OccupancyTracker::Segment>&& history) {
3744 Mutex::Autolock lock(mBufferingStatsMutex);
3745 auto& stats = mBufferingStats[layerName];
3746 for (const auto& segment : history) {
3747 if (!segment.usedThirdBuffer) {
3748 stats.twoBufferTime += segment.totalTime;
3749 }
3750 if (segment.occupancyAverage < 1.0f) {
3751 stats.doubleBufferedTime += segment.totalTime;
3752 } else if (segment.occupancyAverage < 2.0f) {
3753 stats.tripleBufferedTime += segment.totalTime;
3754 }
3755 ++stats.numSegments;
3756 stats.totalTime += segment.totalTime;
3757 }
3758}
3759
Brian Andersond6927fb2016-07-23 23:37:30 -07003760void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3761 result.appendFormat("Layer frame timestamps:\n");
3762
3763 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3764 const size_t count = currentLayers.size();
3765 for (size_t i=0 ; i<count ; i++) {
3766 currentLayers[i]->dumpFrameEvents(result);
3767 }
3768}
3769
Dan Stozae77c7662016-05-13 11:37:28 -07003770void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3771 result.append("Buffering stats:\n");
3772 result.append(" [Layer name] <Active time> <Two buffer> "
3773 "<Double buffered> <Triple buffered>\n");
3774 Mutex::Autolock lock(mBufferingStatsMutex);
3775 typedef std::tuple<std::string, float, float, float> BufferTuple;
3776 std::map<float, BufferTuple, std::greater<float>> sorted;
3777 for (const auto& statsPair : mBufferingStats) {
3778 const char* name = statsPair.first.c_str();
3779 const BufferingStats& stats = statsPair.second;
3780 if (stats.numSegments == 0) {
3781 continue;
3782 }
3783 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3784 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3785 stats.totalTime;
3786 float doubleBufferRatio = static_cast<float>(
3787 stats.doubleBufferedTime) / stats.totalTime;
3788 float tripleBufferRatio = static_cast<float>(
3789 stats.tripleBufferedTime) / stats.totalTime;
3790 sorted.insert({activeTime, {name, twoBufferRatio,
3791 doubleBufferRatio, tripleBufferRatio}});
3792 }
3793 for (const auto& sortedPair : sorted) {
3794 float activeTime = sortedPair.first;
3795 const BufferTuple& values = sortedPair.second;
3796 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3797 std::get<0>(values).c_str(), activeTime,
3798 std::get<1>(values), std::get<2>(values),
3799 std::get<3>(values));
3800 }
3801 result.append("\n");
3802}
3803
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003804void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3805 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003806 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003807
3808 // TODO: print out if wide-color mode is active or not
3809
3810 for (size_t d = 0; d < mDisplays.size(); d++) {
3811 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3812 int32_t hwcId = displayDevice->getHwcDisplayId();
3813 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3814 continue;
3815 }
3816
3817 result.appendFormat("Display %d color modes:\n", hwcId);
3818 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3819 for (auto&& mode : modes) {
3820 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3821 }
3822
3823 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3824 result.appendFormat(" Current color mode: %s (%d)\n",
3825 decodeColorMode(currentMode).c_str(), currentMode);
3826 }
3827 result.append("\n");
3828}
3829
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003830LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003831 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003832 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3833 const State& state = useDrawing ? mDrawingState : mCurrentState;
3834 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003835 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003836 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003837 });
3838
3839 return layersProto;
3840}
3841
Mathias Agopian74d211a2013-04-22 16:55:35 +02003842void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3843 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003844{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003845 bool colorize = false;
3846 if (index < args.size()
3847 && (args[index] == String16("--color"))) {
3848 colorize = true;
3849 index++;
3850 }
3851
3852 Colorizer colorizer(colorize);
3853
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003854 // figure out if we're stuck somewhere
3855 const nsecs_t now = systemTime();
3856 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3857 const nsecs_t inTransaction(mDebugInTransaction);
3858 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3859 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3860
3861 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003862 * Dump library configuration.
3863 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003864
3865 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003866 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003867 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003868 appendSfConfigString(result);
3869 appendUiConfigString(result);
3870 appendGuiConfigString(result);
3871 result.append("\n");
3872
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003873 result.append("\nWide-Color information:\n");
3874 dumpWideColorInfo(result);
3875
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003876 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003877 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003878 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003879 result.append(SyncFeatures::getInstance().toString());
3880 result.append("\n");
3881
Dan Stoza9e56aa02015-11-02 13:00:03 -08003882 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3883
Andy McFadden41d67d72014-04-25 16:58:34 -07003884 colorizer.bold(result);
3885 result.append("DispSync configuration: ");
3886 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003887 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003888 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003889 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003890 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003891 result.append("\n");
3892
Dan Stozab90cf072015-03-05 11:05:59 -08003893 // Dump static screen stats
3894 result.append("\n");
3895 dumpStaticScreenStats(result);
3896 result.append("\n");
3897
Dan Stozae77c7662016-05-13 11:37:28 -07003898 dumpBufferingStats(result);
3899
Andy McFadden4803b742012-09-24 19:07:20 -07003900 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003901 * Dump the visible layer list
3902 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003903 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003904 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003905 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003906
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003907 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003908 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3909 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003910
3911 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003912 * Dump Display state
3913 */
3914
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003915 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003916 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003917 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003918 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3919 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003920 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003921 }
3922
3923 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003924 * Dump SurfaceFlinger global state
3925 */
3926
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003927 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003928 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003929 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003930
Mathias Agopian888c8222012-08-04 21:10:38 -07003931 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003932 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003933
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003934 colorizer.bold(result);
3935 result.appendFormat("EGL implementation : %s\n",
3936 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3937 colorizer.reset(result);
3938 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003939 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003940
Mathias Agopian875d8e12013-06-07 15:35:48 -07003941 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003942
Mathias Agopian42977342012-08-05 00:40:46 -07003943 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003944 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3945 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003946 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003947 " last eglSwapBuffers() time: %f us\n"
3948 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003949 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003950 " refresh-rate : %f fps\n"
3951 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003952 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003953 " gpu_to_cpu_unsupported : %d\n"
3954 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003955 mLastSwapBufferTime/1000.0,
3956 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003957 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003958 1e9 / activeConfig->getVsyncPeriod(),
3959 activeConfig->getDpiX(),
3960 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003961 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003962
Mathias Agopian74d211a2013-04-22 16:55:35 +02003963 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003964 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003965
Mathias Agopian74d211a2013-04-22 16:55:35 +02003966 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003967 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003968
3969 /*
3970 * VSYNC state
3971 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003972 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003973 result.append("\n");
3974
3975 /*
3976 * HWC layer minidump
3977 */
3978 for (size_t d = 0; d < mDisplays.size(); d++) {
3979 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3980 int32_t hwcId = displayDevice->getHwcDisplayId();
3981 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3982 continue;
3983 }
3984
3985 result.appendFormat("Display %d HWC layers:\n", hwcId);
3986 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003987 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003988 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003989 });
Dan Stozae22aec72016-08-01 13:20:59 -07003990 result.append("\n");
3991 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003992
3993 /*
3994 * Dump HWComposer state
3995 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003996 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003997 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003998 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003999 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004000 result.appendFormat(" h/w composer %s\n",
4001 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004002 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004003
4004 /*
4005 * Dump gralloc state
4006 */
4007 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4008 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004009
4010 /*
4011 * Dump VrFlinger state if in use.
4012 */
4013 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4014 result.append("VrFlinger state:\n");
4015 result.append(mVrFlinger->Dump().c_str());
4016 result.append("\n");
4017 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004018}
4019
Mathias Agopian13127d82013-03-05 17:47:11 -08004020const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004021SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004022 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004023 wp<IBinder> dpy;
4024 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4025 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4026 dpy = mDisplays.keyAt(i);
4027 break;
4028 }
4029 }
4030 if (dpy == NULL) {
4031 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4032 // Just use the primary display so we have something to return
4033 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4034 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004035 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004036}
4037
Keun young Park63f165f2012-08-31 10:53:36 -07004038bool SurfaceFlinger::startDdmConnection()
4039{
4040 void* libddmconnection_dso =
4041 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4042 if (!libddmconnection_dso) {
4043 return false;
4044 }
4045 void (*DdmConnection_start)(const char* name);
4046 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004047 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004048 if (!DdmConnection_start) {
4049 dlclose(libddmconnection_dso);
4050 return false;
4051 }
4052 (*DdmConnection_start)(getServiceName());
4053 return true;
4054}
4055
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004056status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004057 switch (code) {
4058 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004059 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004060 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004061 case CLEAR_ANIMATION_FRAME_STATS:
4062 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004063 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004064 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004065 case ENABLE_VSYNC_INJECTIONS:
4066 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004067 {
4068 // codes that require permission check
4069 IPCThreadState* ipc = IPCThreadState::self();
4070 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004071 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004072 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004073 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004074 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004075 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004076 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004077 break;
4078 }
Robert Carr1db73f62016-12-21 12:58:51 -08004079 /*
4080 * Calling setTransactionState is safe, because you need to have been
4081 * granted a reference to Client* and Handle* to do anything with it.
4082 *
4083 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4084 */
4085 case SET_TRANSACTION_STATE:
4086 case CREATE_SCOPED_CONNECTION:
4087 {
4088 return OK;
4089 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004090 case CAPTURE_SCREEN:
4091 {
4092 // codes that require permission check
4093 IPCThreadState* ipc = IPCThreadState::self();
4094 const int pid = ipc->getCallingPid();
4095 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004096 if ((uid != AID_GRAPHICS) &&
4097 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004098 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004099 return PERMISSION_DENIED;
4100 }
4101 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004102 }
chaviwa76b2712017-09-20 12:02:26 -07004103 case CAPTURE_LAYERS: {
4104 IPCThreadState* ipc = IPCThreadState::self();
4105 const int pid = ipc->getCallingPid();
4106 const int uid = ipc->getCallingUid();
4107 if ((uid != AID_GRAPHICS) &&
4108 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4109 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4110 return PERMISSION_DENIED;
4111 }
4112 break;
4113 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004114 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004115 return OK;
4116}
4117
4118status_t SurfaceFlinger::onTransact(
4119 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4120{
4121 status_t credentialCheck = CheckTransactCodeCredentials(code);
4122 if (credentialCheck != OK) {
4123 return credentialCheck;
4124 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004126 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4127 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004128 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004129 IPCThreadState* ipc = IPCThreadState::self();
4130 const int uid = ipc->getCallingUid();
4131 if (CC_UNLIKELY(uid != AID_SYSTEM
4132 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004133 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004134 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004135 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136 return PERMISSION_DENIED;
4137 }
4138 int n;
4139 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004140 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004141 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004142 return NO_ERROR;
4143 case 1002: // SHOW_UPDATES
4144 n = data.readInt32();
4145 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004146 invalidateHwcGeometry();
4147 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004148 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004149 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004150 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004151 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004152 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004153 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004154 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004155 setTransactionFlags(
4156 eTransactionNeeded|
4157 eDisplayTransactionNeeded|
4158 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004159 return NO_ERROR;
4160 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004161 case 1006:{ // send empty update
4162 signalRefresh();
4163 return NO_ERROR;
4164 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004165 case 1008: // toggle use of hw composer
4166 n = data.readInt32();
4167 mDebugDisableHWC = n ? 1 : 0;
4168 invalidateHwcGeometry();
4169 repaintEverything();
4170 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004171 case 1009: // toggle use of transform hint
4172 n = data.readInt32();
4173 mDebugDisableTransformHint = n ? 1 : 0;
4174 invalidateHwcGeometry();
4175 repaintEverything();
4176 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004177 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004178 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004179 reply->writeInt32(0);
4180 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004181 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004182 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004183 return NO_ERROR;
4184 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004185 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004186 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004187 return NO_ERROR;
4188 }
4189 case 1014: {
4190 // daltonize
4191 n = data.readInt32();
4192 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004193 case 1:
4194 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4195 break;
4196 case 2:
4197 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4198 break;
4199 case 3:
4200 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4201 break;
4202 default:
4203 mDaltonizer.setType(ColorBlindnessType::None);
4204 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004205 }
4206 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004207 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004208 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004209 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004210 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004211 invalidateHwcGeometry();
4212 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004213 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004214 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004215 case 1015: {
4216 // apply a color matrix
4217 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004218 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004219 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004220 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004221 for (size_t j = 0; j < 4; j++) {
4222 mColorMatrix[i][j] = data.readFloat();
4223 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004224 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004225 } else {
4226 mColorMatrix = mat4();
4227 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004228
4229 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4230 // the division by w in the fragment shader
4231 float4 lastRow(transpose(mColorMatrix)[3]);
4232 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4233 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4234 }
4235
Alan Viverette9c5a3332013-09-12 20:04:35 -07004236 invalidateHwcGeometry();
4237 repaintEverything();
4238 return NO_ERROR;
4239 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004240 // This is an experimental interface
4241 // Needs to be shifted to proper binder interface when we productize
4242 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004243 n = data.readInt32();
4244 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004245 return NO_ERROR;
4246 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004247 case 1017: {
4248 n = data.readInt32();
4249 mForceFullDamage = static_cast<bool>(n);
4250 return NO_ERROR;
4251 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004252 case 1018: { // Modify Choreographer's phase offset
4253 n = data.readInt32();
4254 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4255 return NO_ERROR;
4256 }
4257 case 1019: { // Modify SurfaceFlinger's phase offset
4258 n = data.readInt32();
4259 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4260 return NO_ERROR;
4261 }
Irvel468051e2016-06-13 16:44:44 -07004262 case 1020: { // Layer updates interceptor
4263 n = data.readInt32();
4264 if (n) {
4265 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004266 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004267 }
4268 else{
4269 ALOGV("Interceptor disabled");
4270 mInterceptor.disable();
4271 }
4272 return NO_ERROR;
4273 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004274 case 1021: { // Disable HWC virtual displays
4275 n = data.readInt32();
4276 mUseHwcVirtualDisplays = !n;
4277 return NO_ERROR;
4278 }
Romain Guy0147a172017-06-01 13:53:56 -07004279 case 1022: { // Set saturation boost
4280 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4281
4282 invalidateHwcGeometry();
4283 repaintEverything();
4284 return NO_ERROR;
4285 }
Romain Guy54f154a2017-10-24 21:40:32 +01004286 case 1023: { // Set native mode
4287 mForceNativeColorMode = data.readInt32() == 1;
4288
4289 invalidateHwcGeometry();
4290 repaintEverything();
4291 return NO_ERROR;
4292 }
4293 case 1024: { // Is wide color gamut rendering/color management supported?
4294 reply->writeBool(hasWideColorDisplay);
4295 return NO_ERROR;
4296 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004297 case 1025: { // tracing
4298 n = data.readInt32();
4299 if (n) {
4300 ALOGV("LayerTracing enabled");
4301 mTracing.enable();
4302 doTracing("tracing.enable");
4303 reply->writeInt32(NO_ERROR);
4304 } else {
4305 ALOGV("LayerTracing disabled");
4306 status_t err = mTracing.disable();
4307 reply->writeInt32(err);
4308 }
4309 return NO_ERROR;
4310 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004311 }
4312 }
4313 return err;
4314}
4315
Steven Thomas6d8110b2017-08-31 18:24:21 -07004316void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004317 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004318 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004319}
4320
Steven Thomas6d8110b2017-08-31 18:24:21 -07004321void SurfaceFlinger::repaintEverything() {
4322 ConditionalLock _l(mStateLock,
4323 std::this_thread::get_id() != mMainThreadId);
4324 repaintEverythingLocked();
4325}
4326
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004327// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4328class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004329public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004330 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4331 ~WindowDisconnector() {
4332 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004333 }
4334
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004335private:
4336 ANativeWindow* mWindow;
4337 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004338};
4339
chaviwa252d892017-11-20 17:54:25 -08004340status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4341 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4342 int32_t minLayerZ, int32_t maxLayerZ,
4343 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004344 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004345 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004346
chaviwa76b2712017-09-20 12:02:26 -07004347 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4348
4349 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4350 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4351
4352 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4353 device, minLayerZ, maxLayerZ, std::placeholders::_1);
chaviwa252d892017-11-20 17:54:25 -08004354 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004355}
4356
4357status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
chaviwa252d892017-11-20 17:54:25 -08004358 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
4359 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004360 ATRACE_CALL();
4361
4362 class LayerRenderArea : public RenderArea {
4363 public:
chaviw7206d492017-11-10 16:16:12 -08004364 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
chaviwa252d892017-11-20 17:54:25 -08004365 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004366 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004367 const Transform& getTransform() const override {
4368 // Make the top level transform the inverse the transform and it's parent so it sets
4369 // the whole capture back to 0,0
4370 return *new Transform(mLayer->getTransform().inverse());
4371 }
4372 Rect getBounds() const override {
4373 const Layer::State& layerState(mLayer->getDrawingState());
4374 return Rect(layerState.active.w, layerState.active.h);
4375 }
4376 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4377 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4378 bool isSecure() const override { return false; }
4379 bool needsFiltering() const override { return false; }
4380
chaviw7206d492017-11-10 16:16:12 -08004381 Rect getSourceCrop() const override {
4382 if (mCrop.isEmpty()) {
4383 return getBounds();
4384 } else {
4385 return mCrop;
4386 }
4387 }
chaviwa76b2712017-09-20 12:02:26 -07004388 bool getWideColorSupport() const override { return false; }
4389 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4390
4391 private:
chaviw7206d492017-11-10 16:16:12 -08004392 const sp<Layer> mLayer;
4393 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004394 };
4395
4396 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4397 auto parent = layerHandle->owner.promote();
4398
chaviw7206d492017-11-10 16:16:12 -08004399 if (parent == nullptr || parent->isPendingRemoval()) {
4400 ALOGE("captureLayers called with a removed parent");
4401 return NAME_NOT_FOUND;
4402 }
4403
4404 Rect crop(sourceCrop);
4405 if (sourceCrop.width() <= 0) {
4406 crop.left = 0;
4407 crop.right = parent->getCurrentState().active.w;
4408 }
4409
4410 if (sourceCrop.height() <= 0) {
4411 crop.top = 0;
4412 crop.bottom = parent->getCurrentState().active.h;
4413 }
4414
4415 int32_t reqWidth = crop.width() * frameScale;
4416 int32_t reqHeight = crop.height() * frameScale;
4417
4418 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4419
chaviwa76b2712017-09-20 12:02:26 -07004420 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4421 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4422 if (!layer->isVisible()) {
4423 return;
4424 }
4425 visitor(layer);
4426 });
4427 };
chaviwa252d892017-11-20 17:54:25 -08004428 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004429}
4430
4431status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4432 TraverseLayersFunction traverseLayers,
chaviwa252d892017-11-20 17:54:25 -08004433 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004434 bool useIdentityTransform) {
4435 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004436
chaviwa76b2712017-09-20 12:02:26 -07004437 renderArea.updateDimensions();
4438
chaviwa252d892017-11-20 17:54:25 -08004439 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4440 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4441 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4442 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004443
4444 // This mutex protects syncFd and captureResult for communication of the return values from the
4445 // main thread back to this Binder thread
4446 std::mutex captureMutex;
4447 std::condition_variable captureCondition;
4448 std::unique_lock<std::mutex> captureLock(captureMutex);
4449 int syncFd = -1;
4450 std::optional<status_t> captureResult;
4451
4452 sp<LambdaMessage> message = new LambdaMessage([&]() {
4453 // If there is a refresh pending, bug out early and tell the binder thread to try again
4454 // after the refresh.
4455 if (mRefreshPending) {
4456 ATRACE_NAME("Skipping screenshot for now");
4457 std::unique_lock<std::mutex> captureLock(captureMutex);
4458 captureResult = std::make_optional<status_t>(EAGAIN);
4459 captureCondition.notify_one();
4460 return;
4461 }
4462
4463 status_t result = NO_ERROR;
4464 int fd = -1;
4465 {
4466 Mutex::Autolock _l(mStateLock);
chaviwa252d892017-11-20 17:54:25 -08004467 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4468 useIdentityTransform, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004469 }
4470
4471 {
4472 std::unique_lock<std::mutex> captureLock(captureMutex);
4473 syncFd = fd;
4474 captureResult = std::make_optional<status_t>(result);
4475 captureCondition.notify_one();
4476 }
4477 });
4478
chaviwa252d892017-11-20 17:54:25 -08004479 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004480 if (result == NO_ERROR) {
4481 captureCondition.wait(captureLock, [&]() { return captureResult; });
4482 while (*captureResult == EAGAIN) {
4483 captureResult.reset();
4484 result = postMessageAsync(message);
4485 if (result != NO_ERROR) {
4486 return result;
4487 }
4488 captureCondition.wait(captureLock, [&]() { return captureResult; });
4489 }
4490 result = *captureResult;
4491 }
4492
4493 if (result == NO_ERROR) {
chaviwa252d892017-11-20 17:54:25 -08004494 sync_wait(syncFd, -1);
4495 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004496 }
chaviwa252d892017-11-20 17:54:25 -08004497
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004498 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004499}
4500
chaviwa76b2712017-09-20 12:02:26 -07004501void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4502 TraverseLayersFunction traverseLayers, bool yswap,
4503 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004504 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004505
Mathias Agopian3f844832013-08-07 21:24:32 -07004506 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004507
4508 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004509 const auto raWidth = renderArea.getWidth();
4510 const auto raHeight = renderArea.getHeight();
4511
4512 const auto reqWidth = renderArea.getReqWidth();
4513 const auto reqHeight = renderArea.getReqHeight();
4514 Rect sourceCrop = renderArea.getSourceCrop();
4515
4516 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4517 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004518
Dan Stozac1879002014-05-22 15:59:05 -07004519 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004520 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004521 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004522 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004523 }
4524
4525 // ensure that sourceCrop is inside screen
4526 if (sourceCrop.left < 0) {
4527 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4528 }
chaviwa76b2712017-09-20 12:02:26 -07004529 if (sourceCrop.right > raWidth) {
4530 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004531 }
4532 if (sourceCrop.top < 0) {
4533 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4534 }
chaviwa76b2712017-09-20 12:02:26 -07004535 if (sourceCrop.bottom > raHeight) {
4536 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004537 }
4538
chaviwa76b2712017-09-20 12:02:26 -07004539 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
chaviwa252d892017-11-20 17:54:25 -08004540 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4541 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004542
Mathias Agopian180f10d2013-04-10 22:55:41 -07004543 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004544 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004545
4546 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004547 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4548 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004549 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004550
4551 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004552 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004553
chaviwa76b2712017-09-20 12:02:26 -07004554 traverseLayers([&](Layer* layer) {
4555 if (filtering) layer->setFiltering(true);
4556 layer->draw(renderArea, useIdentityTransform);
4557 if (filtering) layer->setFiltering(false);
4558 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004559}
4560
Dan Stozaabcda352017-06-01 14:37:39 -07004561// A simple RAII class that holds an EGLImage and destroys it either:
4562// a) When the destroy() method is called
4563// b) When the object goes out of scope
4564class ImageHolder {
4565public:
4566 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4567 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004568
Dan Stozaabcda352017-06-01 14:37:39 -07004569 void destroy() {
4570 if (mImage != EGL_NO_IMAGE_KHR) {
4571 eglDestroyImageKHR(mDisplay, mImage);
4572 mImage = EGL_NO_IMAGE_KHR;
4573 }
4574 }
4575
4576private:
4577 const EGLDisplay mDisplay;
4578 EGLImageKHR mImage;
4579};
4580
chaviwa76b2712017-09-20 12:02:26 -07004581status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4582 TraverseLayersFunction traverseLayers,
4583 ANativeWindowBuffer* buffer,
chaviwa252d892017-11-20 17:54:25 -08004584 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004585 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004586 ATRACE_CALL();
4587
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004588 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004589
4590 traverseLayers([&](Layer* layer) {
4591 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4592 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004593
chaviwa252d892017-11-20 17:54:25 -08004594 if (secureLayerIsVisible) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004595 ALOGW("FB is protected: PERMISSION_DENIED");
4596 return PERMISSION_DENIED;
4597 }
4598
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004599 int syncFd = -1;
4600 // create an EGLImage from the buffer so we can later
4601 // turn it into a texture
4602 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4603 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4604 if (image == EGL_NO_IMAGE_KHR) {
4605 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004606 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004607
Dan Stozaabcda352017-06-01 14:37:39 -07004608 // This will automatically destroy the image if we return before calling its destroy method
4609 ImageHolder imageHolder(mEGLDisplay, image);
4610
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004611 // this binds the given EGLImage as a framebuffer for the
4612 // duration of this scope.
4613 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004614 if (imageBond.getStatus() != NO_ERROR) {
4615 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004616 return INVALID_OPERATION;
4617 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004618
Dan Stozaabcda352017-06-01 14:37:39 -07004619 // this will in fact render into our dequeued buffer
4620 // via an FBO, which means we didn't have to create
4621 // an EGLSurface and therefore we're not
4622 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004623 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004624
Dan Stozaabcda352017-06-01 14:37:39 -07004625 // Attempt to create a sync khr object that can produce a sync point. If that
4626 // isn't available, create a non-dupable sync object in the fallback path and
4627 // wait on it directly.
4628 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4629 if (!DEBUG_SCREENSHOTS) {
4630 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4631 // native fence fd will not be populated until flush() is done.
4632 getRenderEngine().flush();
4633 }
4634
4635 if (sync != EGL_NO_SYNC_KHR) {
4636 // get the sync fd
4637 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4638 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4639 ALOGW("captureScreen: failed to dup sync khr object");
4640 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004641 }
Dan Stozaabcda352017-06-01 14:37:39 -07004642 eglDestroySyncKHR(mEGLDisplay, sync);
4643 } else {
4644 // fallback path
4645 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004646 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004647 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4648 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4649 EGLint eglErr = eglGetError();
4650 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4651 ALOGW("captureScreen: fence wait timed out");
4652 } else {
4653 ALOGW_IF(eglErr != EGL_SUCCESS,
4654 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004655 }
4656 eglDestroySyncKHR(mEGLDisplay, sync);
4657 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004658 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004659 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004660 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004661 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004662
4663 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004664 const auto reqWidth = renderArea.getReqWidth();
4665 const auto reqHeight = renderArea.getReqHeight();
4666
Dan Stozaabcda352017-06-01 14:37:39 -07004667 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4668 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004669 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004670 delete [] pixels;
4671 }
4672
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004673 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004674 imageHolder.destroy();
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004675 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004676}
4677
Mathias Agopiand5556842013-09-19 17:08:37 -07004678void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004679 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004680 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004681 for (size_t y = 0; y < h; y++) {
4682 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4683 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004684 if (p[x] != 0xFF000000) return;
4685 }
4686 }
chaviwa76b2712017-09-20 12:02:26 -07004687 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004688
Robert Carr2047fae2016-11-28 14:09:09 -08004689 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004690 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004691 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004692 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4693 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4694 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4695 static_cast<float>(state.color.a));
4696 i++;
4697 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004698 }
4699}
4700
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004701// ---------------------------------------------------------------------------
4702
Dan Stoza412903f2017-04-27 13:42:17 -07004703void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4704 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004705}
4706
Dan Stoza412903f2017-04-27 13:42:17 -07004707void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4708 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004709}
4710
chaviwa76b2712017-09-20 12:02:26 -07004711void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4712 int32_t maxLayerZ,
4713 const LayerVector::Visitor& visitor) {
4714 // We loop through the first level of layers without traversing,
4715 // as we need to interpret min/max layer Z in the top level Z space.
4716 for (const auto& layer : mDrawingState.layersSortedByZ) {
4717 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4718 continue;
4719 }
4720 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004721 // relative layers are traversed in Layer::traverseInZOrder
4722 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004723 continue;
4724 }
4725 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4726 if (!layer->isVisible()) {
4727 return;
4728 }
4729 visitor(layer);
4730 });
4731 }
4732}
4733
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004734}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004735
4736
4737#if defined(__gl_h_)
4738#error "don't include gl/gl.h in this file"
4739#endif
4740
4741#if defined(__gl2_h_)
4742#error "don't include gl2/gl2.h in this file"
chaviwa252d892017-11-20 17:54:25 -08004743#endif