blob: 4acd4482939eb14a493d87c72b13069cbc53ff15 [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 // initialize EGL for the default display
598 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
599 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800600
Steven Thomasb02664d2017-07-26 18:48:28 -0700601 // start the EventThread
602 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
603 vsyncPhaseOffsetNs, true, "app");
604 mEventThread = new EventThread(vsyncSrc, *this, false);
605 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
606 sfVsyncPhaseOffsetNs, true, "sf");
607 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
608 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
611 struct sched_param param = {0};
612 param.sched_priority = 2;
613 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
614 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
615 }
616 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
617 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800618 }
619
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 // Get a RenderEngine for the given display / config (can't fail)
621 mRenderEngine = RenderEngine::create(mEGLDisplay,
622 HAL_PIXEL_FORMAT_RGBA_8888,
623 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 // retrieve the EGL context that was selected/created
626 mEGLContext = mRenderEngine->getEGLContext();
627
628 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
629 "couldn't create EGLContext");
630
631 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
632 "Starting with vr flinger active is not currently supported.");
633 mHwc.reset(new HWComposer(mHwcServiceName));
634 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800635
Steven Thomas050b2c82017-03-06 11:45:16 -0800636 if (useVrFlinger) {
637 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700638 // This callback is called from the vr flinger dispatch thread. We
639 // need to call signalTransaction(), which requires holding
640 // mStateLock when we're not on the main thread. Acquiring
641 // mStateLock from the vr flinger dispatch thread might trigger a
642 // deadlock in surface flinger (see b/66916578), so post a message
643 // to be handled on the main thread instead.
644 sp<LambdaMessage> message = new LambdaMessage([=]() {
645 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
646 mVrFlingerRequestsDisplay = requestDisplay;
647 signalTransaction();
648 });
649 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800650 };
651 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800652 mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
653 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800654 if (!mVrFlinger) {
655 ALOGE("Failed to start vrflinger");
656 }
657 }
658
Jamie Gennisd1700752013-10-14 12:22:52 -0700659 mEventControlThread = new EventControlThread(this);
660 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
661
Mathias Agopian92a979a2012-08-02 18:32:23 -0700662 // initialize our drawing state
663 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700664
Andy McFadden13a082e2012-08-24 10:16:42 -0700665 // set initial conditions (e.g. unblank default device)
666 initializeDisplays();
667
Dan Stoza4e637772016-07-28 13:31:51 -0700668 mRenderEngine->primeCache();
669
Wei Wangf9b05ee2017-07-19 20:59:39 -0700670 // Inform native graphics APIs whether the present timestamp is supported:
671 if (getHwComposer().hasCapability(
672 HWC2::Capability::PresentFenceIsNotReliable)) {
673 mStartPropertySetThread = new StartPropertySetThread(false);
674 } else {
675 mStartPropertySetThread = new StartPropertySetThread(true);
676 }
677
678 if (mStartPropertySetThread->Start() != NO_ERROR) {
679 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800680 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800681
Dan Stoza9e56aa02015-11-02 13:00:03 -0800682 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700683}
684
Romain Guy11d63f42017-07-20 12:47:14 -0700685void SurfaceFlinger::readPersistentProperties() {
686 char value[PROPERTY_VALUE_MAX];
687
688 property_get("persist.sys.sf.color_saturation", value, "1.0");
689 mSaturation = atof(value);
690 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100691
692 property_get("persist.sys.sf.native_mode", value, "0");
693 mForceNativeColorMode = atoi(value) == 1;
694 if (mForceNativeColorMode) {
695 ALOGV("Forcing native color mode");
696 }
Romain Guy11d63f42017-07-20 12:47:14 -0700697}
698
Mathias Agopiana67e4182012-06-19 17:26:12 -0700699void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800700 // Start boot animation service by setting a property mailbox
701 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700702 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800703 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700704 if (mStartPropertySetThread->join() != NO_ERROR) {
705 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800706 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700707}
708
Mathias Agopian875d8e12013-06-07 15:35:48 -0700709size_t SurfaceFlinger::getMaxTextureSize() const {
710 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700711}
712
Mathias Agopian875d8e12013-06-07 15:35:48 -0700713size_t SurfaceFlinger::getMaxViewportDims() const {
714 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700715}
716
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800717// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800718
Jamie Gennis582270d2011-08-17 18:19:00 -0700719bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800720 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800721 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800722 return authenticateSurfaceTextureLocked(bufferProducer);
723}
724
725bool SurfaceFlinger::authenticateSurfaceTextureLocked(
726 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800727 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700728 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800729}
730
Brian Anderson6b376712017-04-04 10:51:39 -0700731status_t SurfaceFlinger::getSupportedFrameTimestamps(
732 std::vector<FrameEvent>* outSupported) const {
733 *outSupported = {
734 FrameEvent::REQUESTED_PRESENT,
735 FrameEvent::ACQUIRE,
736 FrameEvent::LATCH,
737 FrameEvent::FIRST_REFRESH_START,
738 FrameEvent::LAST_REFRESH_START,
739 FrameEvent::GPU_COMPOSITION_DONE,
740 FrameEvent::DEQUEUE_READY,
741 FrameEvent::RELEASE,
742 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700743 ConditionalLock _l(mStateLock,
744 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700745 if (!getHwComposer().hasCapability(
746 HWC2::Capability::PresentFenceIsNotReliable)) {
747 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
748 }
749 return NO_ERROR;
750}
751
Dan Stoza7f7da322014-05-02 15:26:25 -0700752status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
753 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700754 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700755 return BAD_VALUE;
756 }
757
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500758 if (!display.get())
759 return NAME_NOT_FOUND;
760
Jesse Hall692c7232012-11-08 15:41:56 -0800761 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700762 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800763 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700764 type = i;
765 break;
766 }
767 }
768
769 if (type < 0) {
770 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700771 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700772
Mathias Agopian8b736f12012-08-13 17:54:26 -0700773 // TODO: Not sure if display density should handled by SF any longer
774 class Density {
775 static int getDensityFromProperty(char const* propName) {
776 char property[PROPERTY_VALUE_MAX];
777 int density = 0;
778 if (property_get(propName, property, NULL) > 0) {
779 density = atoi(property);
780 }
781 return density;
782 }
783 public:
784 static int getEmuDensity() {
785 return getDensityFromProperty("qemu.sf.lcd_density"); }
786 static int getBuildDensity() {
787 return getDensityFromProperty("ro.sf.lcd_density"); }
788 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700789
Dan Stoza7f7da322014-05-02 15:26:25 -0700790 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700791
Steven Thomas6d8110b2017-08-31 18:24:21 -0700792 ConditionalLock _l(mStateLock,
793 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800794 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700795 DisplayInfo info = DisplayInfo();
796
Dan Stoza9e56aa02015-11-02 13:00:03 -0800797 float xdpi = hwConfig->getDpiX();
798 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700799
800 if (type == DisplayDevice::DISPLAY_PRIMARY) {
801 // The density of the device is provided by a build property
802 float density = Density::getBuildDensity() / 160.0f;
803 if (density == 0) {
804 // the build doesn't provide a density -- this is wrong!
805 // use xdpi instead
806 ALOGE("ro.sf.lcd_density must be defined as a build property");
807 density = xdpi / 160.0f;
808 }
809 if (Density::getEmuDensity()) {
810 // if "qemu.sf.lcd_density" is specified, it overrides everything
811 xdpi = ydpi = density = Density::getEmuDensity();
812 density /= 160.0f;
813 }
814 info.density = density;
815
816 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700817 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000818 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700819 } else {
820 // TODO: where should this value come from?
821 static const int TV_DENSITY = 213;
822 info.density = TV_DENSITY / 160.0f;
823 info.orientation = 0;
824 }
825
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826 info.w = hwConfig->getWidth();
827 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700828 info.xdpi = xdpi;
829 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900831 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800832
Andy McFadden91b2ca82014-06-13 14:04:23 -0700833 // This is how far in advance a buffer must be queued for
834 // presentation at a given time. If you want a buffer to appear
835 // on the screen at time N, you must submit the buffer before
836 // (N - presentationDeadline).
837 //
838 // Normally it's one full refresh period (to give SF a chance to
839 // latch the buffer), but this can be reduced by configuring a
840 // DispSync offset. Any additional delays introduced by the hardware
841 // composer or panel must be accounted for here.
842 //
843 // We add an additional 1ms to allow for processing time and
844 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800845 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800846 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700847
848 // All non-virtual displays are currently considered secure.
849 info.secure = true;
850
Michael Wright28f24d02016-07-12 13:30:53 -0700851 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700852 }
853
Dan Stoza7f7da322014-05-02 15:26:25 -0700854 return NO_ERROR;
855}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700856
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800857status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700858 DisplayStatInfo* stats) {
859 if (stats == NULL) {
860 return BAD_VALUE;
861 }
862
863 // FIXME for now we always return stats for the primary display
864 memset(stats, 0, sizeof(*stats));
865 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
866 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
867 return NO_ERROR;
868}
869
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700870int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800871 if (display == NULL) {
872 ALOGE("%s : display is NULL", __func__);
873 return BAD_VALUE;
874 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700875
876 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700877 if (device != NULL) {
878 return device->getActiveConfig();
879 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700880
Dan Stoza24a42e92015-03-09 10:04:11 -0700881 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700882}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700883
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700884void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
885 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
886 this);
887 int32_t type = hw->getDisplayType();
888 int currentMode = hw->getActiveConfig();
889
890 if (mode == currentMode) {
891 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
892 return;
893 }
894
895 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
896 ALOGW("Trying to set config for virtual display");
897 return;
898 }
899
900 hw->setActiveConfig(mode);
901 getHwComposer().setActiveConfig(type, mode);
902}
903
904status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
905 class MessageSetActiveConfig: public MessageBase {
906 SurfaceFlinger& mFlinger;
907 sp<IBinder> mDisplay;
908 int mMode;
909 public:
910 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
911 int mode) :
912 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
913 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700914 Vector<DisplayInfo> configs;
915 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700916 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700917 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700918 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700919 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700920 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700921 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
922 if (hw == NULL) {
923 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700924 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700925 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
926 ALOGW("Attempt to set active config = %d for virtual display",
927 mMode);
928 } else {
929 mFlinger.setActiveConfigInternal(hw, mMode);
930 }
931 return true;
932 }
933 };
934 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
935 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700936 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700937}
Michael Wright28f24d02016-07-12 13:30:53 -0700938status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
939 Vector<android_color_mode_t>* outColorModes) {
940 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
941 return BAD_VALUE;
942 }
943
944 if (!display.get()) {
945 return NAME_NOT_FOUND;
946 }
947
948 int32_t type = NAME_NOT_FOUND;
949 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
950 if (display == mBuiltinDisplays[i]) {
951 type = i;
952 break;
953 }
954 }
955
956 if (type < 0) {
957 return type;
958 }
959
Steven Thomas6d8110b2017-08-31 18:24:21 -0700960 std::vector<android_color_mode_t> modes;
961 {
962 ConditionalLock _l(mStateLock,
963 std::this_thread::get_id() != mMainThreadId);
964 modes = getHwComposer().getColorModes(type);
965 }
Michael Wright28f24d02016-07-12 13:30:53 -0700966 outColorModes->clear();
967 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
968
969 return NO_ERROR;
970}
971
972android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700973 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700974 if (device != nullptr) {
975 return device->getActiveColorMode();
976 }
977 return static_cast<android_color_mode_t>(BAD_VALUE);
978}
979
980void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
981 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700982 int32_t type = hw->getDisplayType();
983 android_color_mode_t currentMode = hw->getActiveColorMode();
984
985 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700986 return;
987 }
988
989 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
990 ALOGW("Trying to set config for virtual display");
991 return;
992 }
993
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600994 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
995 hw->getDisplayType());
996
Michael Wright28f24d02016-07-12 13:30:53 -0700997 hw->setActiveColorMode(mode);
998 getHwComposer().setActiveColorMode(type, mode);
999}
1000
1001
1002status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
1003 android_color_mode_t colorMode) {
1004 class MessageSetActiveColorMode: public MessageBase {
1005 SurfaceFlinger& mFlinger;
1006 sp<IBinder> mDisplay;
1007 android_color_mode_t mMode;
1008 public:
1009 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1010 android_color_mode_t mode) :
1011 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1012 virtual bool handler() {
1013 Vector<android_color_mode_t> modes;
1014 mFlinger.getDisplayColorModes(mDisplay, &modes);
1015 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1016 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001017 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1018 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001019 return true;
1020 }
1021 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1022 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001023 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1024 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001025 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001026 ALOGW("Attempt to set active color mode %s %d for virtual display",
1027 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001028 } else {
1029 mFlinger.setActiveColorModeInternal(hw, mMode);
1030 }
1031 return true;
1032 }
1033 };
1034 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1035 postMessageSync(msg);
1036 return NO_ERROR;
1037}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001038
Svetoslavd85084b2014-03-20 10:28:31 -07001039status_t SurfaceFlinger::clearAnimationFrameStats() {
1040 Mutex::Autolock _l(mStateLock);
1041 mAnimFrameTracker.clearStats();
1042 return NO_ERROR;
1043}
1044
1045status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1046 Mutex::Autolock _l(mStateLock);
1047 mAnimFrameTracker.getStats(outStats);
1048 return NO_ERROR;
1049}
1050
Dan Stozac4f471e2016-03-24 09:31:08 -07001051status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1052 HdrCapabilities* outCapabilities) const {
1053 Mutex::Autolock _l(mStateLock);
1054
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001055 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001056 if (displayDevice == nullptr) {
1057 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1058 return BAD_VALUE;
1059 }
1060
1061 std::unique_ptr<HdrCapabilities> capabilities =
1062 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1063 if (capabilities) {
1064 std::swap(*outCapabilities, *capabilities);
1065 } else {
1066 return BAD_VALUE;
1067 }
1068
1069 return NO_ERROR;
1070}
1071
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001072status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001073 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1074 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001075
Chia-I Wu90f669f2017-10-05 14:24:41 -07001076 if (mInjectVSyncs == enable) {
1077 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001078 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001079
1080 if (enable) {
1081 ALOGV("VSync Injections enabled");
1082 if (mVSyncInjector.get() == nullptr) {
1083 mVSyncInjector = new InjectVSyncSource();
1084 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1085 }
1086 mEventQueue.setEventThread(mInjectorEventThread);
1087 } else {
1088 ALOGV("VSync Injections disabled");
1089 mEventQueue.setEventThread(mSFEventThread);
1090 }
1091
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001092 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001093 });
1094 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095 return NO_ERROR;
1096}
1097
1098status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099 Mutex::Autolock _l(mStateLock);
1100
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001101 if (!mInjectVSyncs) {
1102 ALOGE("VSync Injections not enabled");
1103 return BAD_VALUE;
1104 }
1105 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1106 ALOGV("Injecting VSync inside SurfaceFlinger");
1107 mVSyncInjector->onInjectSyncEvent(when);
1108 }
1109 return NO_ERROR;
1110}
1111
Kalle Raitaa099a242017-01-11 11:17:29 -08001112status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1113 IPCThreadState* ipc = IPCThreadState::self();
1114 const int pid = ipc->getCallingPid();
1115 const int uid = ipc->getCallingUid();
1116 if ((uid != AID_SHELL) &&
1117 !PermissionCache::checkPermission(sDump, pid, uid)) {
1118 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1119 return PERMISSION_DENIED;
1120 }
1121
1122 // Try to acquire a lock for 1s, fail gracefully
1123 const status_t err = mStateLock.timedLock(s2ns(1));
1124 const bool locked = (err == NO_ERROR);
1125 if (!locked) {
1126 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1127 return TIMED_OUT;
1128 }
1129
1130 outLayers->clear();
1131 mCurrentState.traverseInZOrder([&](Layer* layer) {
1132 outLayers->push_back(layer->getLayerDebugInfo());
1133 });
1134
1135 mStateLock.unlock();
1136 return NO_ERROR;
1137}
1138
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001139// ----------------------------------------------------------------------------
1140
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001141sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1142 ISurfaceComposer::VsyncSource vsyncSource) {
1143 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1144 return mSFEventThread->createEventConnection();
1145 } else {
1146 return mEventThread->createEventConnection();
1147 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001148}
1149
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001150// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001151
1152void SurfaceFlinger::waitForEvent() {
1153 mEventQueue.waitMessage();
1154}
1155
1156void SurfaceFlinger::signalTransaction() {
1157 mEventQueue.invalidate();
1158}
1159
1160void SurfaceFlinger::signalLayerUpdate() {
1161 mEventQueue.invalidate();
1162}
1163
1164void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001165 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001166 mEventQueue.refresh();
1167}
1168
1169status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001170 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001171 return mEventQueue.postMessage(msg, reltime);
1172}
1173
1174status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001175 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001176 status_t res = mEventQueue.postMessage(msg, reltime);
1177 if (res == NO_ERROR) {
1178 msg->wait();
1179 }
1180 return res;
1181}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001182
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001183void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001184 do {
1185 waitForEvent();
1186 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001187}
1188
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189void SurfaceFlinger::enableHardwareVsync() {
1190 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001191 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001192 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001193 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1194 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001196 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001197}
1198
Jesse Hall948fe0c2013-10-14 12:56:09 -07001199void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001200 Mutex::Autolock _l(mHWVsyncLock);
1201
Jesse Hall948fe0c2013-10-14 12:56:09 -07001202 if (makeAvailable) {
1203 mHWVsyncAvailable = true;
1204 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001205 // Hardware vsync is not currently available, so abort the resync
1206 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001207 return;
1208 }
1209
Dan Stoza9e56aa02015-11-02 13:00:03 -08001210 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1211 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001212
1213 mPrimaryDispSync.reset();
1214 mPrimaryDispSync.setPeriod(period);
1215
1216 if (!mPrimaryHWVsyncEnabled) {
1217 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001218 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1219 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220 mPrimaryHWVsyncEnabled = true;
1221 }
1222}
1223
Jesse Hall948fe0c2013-10-14 12:56:09 -07001224void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225 Mutex::Autolock _l(mHWVsyncLock);
1226 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001227 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1228 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001229 mPrimaryDispSync.endResync();
1230 mPrimaryHWVsyncEnabled = false;
1231 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001232 if (makeUnavailable) {
1233 mHWVsyncAvailable = false;
1234 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001235}
1236
Tim Murray4a4e4a22016-04-19 16:29:23 +00001237void SurfaceFlinger::resyncWithRateLimit() {
1238 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001239
1240 // No explicit locking is needed here since EventThread holds a lock while calling this method
1241 static nsecs_t sLastResyncAttempted = 0;
1242 const nsecs_t now = systemTime();
1243 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001244 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001245 }
Dan Stoza57164302017-05-08 14:03:54 -07001246 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001247}
1248
Steven Thomasb02664d2017-07-26 18:48:28 -07001249void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1250 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001251 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001252 // Ignore any vsyncs from a previous hardware composer.
1253 if (sequenceId != mComposerSequenceId) {
1254 return;
1255 }
1256
1257 int32_t type;
1258 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001259 return;
1260 }
1261
Jamie Gennisd1700752013-10-14 12:22:52 -07001262 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001263
Jamie Gennisd1700752013-10-14 12:22:52 -07001264 { // Scope for the lock
1265 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001266 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001267 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001268 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001269 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001270
1271 if (needsHwVsync) {
1272 enableHardwareVsync();
1273 } else {
1274 disableHardwareVsync(false);
1275 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001276}
1277
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001278void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001279 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001280 *compositorTiming = mCompositorTiming;
1281}
1282
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001283void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001284 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001285 wp<IBinder> token = mBuiltinDisplays[type];
1286
1287 // All non-virtual displays are currently considered secure.
1288 const bool isSecure = true;
1289
1290 sp<IGraphicBufferProducer> producer;
1291 sp<IGraphicBufferConsumer> consumer;
1292 BufferQueue::createBufferQueue(&producer, &consumer);
1293
1294 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1295
1296 bool hasWideColorModes = false;
1297 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1298 for (android_color_mode_t colorMode : modes) {
1299 switch (colorMode) {
1300 case HAL_COLOR_MODE_DISPLAY_P3:
1301 case HAL_COLOR_MODE_ADOBE_RGB:
1302 case HAL_COLOR_MODE_DCI_P3:
1303 hasWideColorModes = true;
1304 break;
1305 default:
1306 break;
1307 }
1308 }
Romain Guy54f154a2017-10-24 21:40:32 +01001309 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001310 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1311 token, fbs, producer, mRenderEngine->getEGLConfig(),
Romain Guy54f154a2017-10-24 21:40:32 +01001312 useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001313 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001314 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001315 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001316 defaultColorMode = HAL_COLOR_MODE_SRGB;
1317 }
1318 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001319 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001320
1321 // Add the primary display token to mDrawingState so we don't try to
1322 // recreate the DisplayDevice for the primary display.
1323 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1324
1325 // make the GLContext current so that we can create textures when creating
1326 // Layers (which may happens before we render something)
1327 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001328}
1329
Steven Thomasb02664d2017-07-26 18:48:28 -07001330void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1331 hwc2_display_t display, HWC2::Connection connection,
1332 bool primaryDisplay) {
1333 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1334 sequenceId, display,
1335 connection == HWC2::Connection::Connected ?
1336 "connected" : "disconnected",
1337 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001338
Steven Thomasb02664d2017-07-26 18:48:28 -07001339 // Only lock if we're not on the main thread. This function is normally
1340 // called on a hwbinder thread, but for the primary display it's called on
1341 // the main thread with the state lock already held, so don't attempt to
1342 // acquire it here.
1343 ConditionalLock lock(mStateLock,
1344 std::this_thread::get_id() != mMainThreadId);
1345
1346 if (primaryDisplay) {
1347 mHwc->onHotplug(display, connection);
1348 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1349 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001350 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001352 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001353 if (sequenceId != mComposerSequenceId) {
1354 return;
1355 }
1356 if (mHwc->isUsingVrComposer()) {
1357 ALOGE("External displays are not supported by the vr hardware composer.");
1358 return;
1359 }
1360 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001361 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001363 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001364 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001365 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1366 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001367 }
1368 setTransactionFlags(eDisplayTransactionNeeded);
1369
Andy McFadden9e9689c2012-10-10 18:17:51 -07001370 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001371 }
Mathias Agopian86303202012-07-24 22:46:10 -07001372}
1373
Steven Thomasb02664d2017-07-26 18:48:28 -07001374void SurfaceFlinger::onRefreshReceived(int sequenceId,
1375 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001376 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001377 if (sequenceId != mComposerSequenceId) {
1378 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001379 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001380 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001381}
1382
Dan Stoza9e56aa02015-11-02 13:00:03 -08001383void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001384 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001386 getHwComposer().setVsyncEnabled(disp,
1387 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001388}
1389
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001390// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001391void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001392 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001393 // Clear the drawing state so that the logic inside of
1394 // handleTransactionLocked will fire. It will determine the delta between
1395 // mCurrentState and mDrawingState and re-apply all changes when we make the
1396 // transition.
1397 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001398 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001399 mDisplays.clear();
1400}
1401
Steven Thomas050b2c82017-03-06 11:45:16 -08001402void SurfaceFlinger::updateVrFlinger() {
1403 if (!mVrFlinger)
1404 return;
1405 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1406 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001407 return;
1408 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001409
Steven Thomasb02664d2017-07-26 18:48:28 -07001410 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1411 ALOGE("Vr flinger is only supported for remote hardware composer"
1412 " service connections. Ignoring request to transition to vr"
1413 " flinger.");
1414 mVrFlingerRequestsDisplay = false;
1415 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001416 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 int currentDisplayPowerMode = getDisplayDeviceLocked(
1421 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001422
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001424 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001426
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 resetDisplayState();
1428 mHwc.reset(); // Delete the current instance before creating the new one
1429 mHwc.reset(new HWComposer(
1430 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1431 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432
Steven Thomasb02664d2017-07-26 18:48:28 -07001433 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1434 "Switched to non-remote hardware composer");
1435
1436 if (vrFlingerRequestsDisplay) {
1437 mVrFlinger->GrantDisplayOwnership();
1438 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001439 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001440 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441
1442 mVisibleRegionsDirty = true;
1443 invalidateHwcGeometry();
1444
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001445 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001446 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1447 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1448 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001449
Steven Thomasb02664d2017-07-26 18:48:28 -07001450 // Reset the timing values to account for the period of the swapped in HWC
1451 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1452 const nsecs_t period = activeConfig->getVsyncPeriod();
1453 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001454
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 // Use phase of 0 since phase is not known.
1456 // Use latency of 0, which will snap to the ideal latency.
1457 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001458
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001459 android_atomic_or(1, &mRepaintEverything);
1460 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001461}
1462
Mathias Agopian4fec8732012-06-29 14:12:52 -07001463void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001464 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001465 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001467 bool frameMissed = !mHadClientComposition &&
1468 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001469 (mPreviousPresentFence->getSignalTime() ==
1470 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001471 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001472 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001473 signalLayerUpdate();
1474 break;
1475 }
1476
Steven Thomas050b2c82017-03-06 11:45:16 -08001477 // Now that we're going to make it to the handleMessageTransaction()
1478 // call below it's safe to call updateVrFlinger(), which will
1479 // potentially trigger a display handoff.
1480 updateVrFlinger();
1481
Dan Stoza6b9454d2014-11-07 16:00:59 -08001482 bool refreshNeeded = handleMessageTransaction();
1483 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001484 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001485 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001486 // Signal a refresh if a transaction modified the window state,
1487 // a new buffer was latched, or if HWC has requested a full
1488 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001489 signalRefresh();
1490 }
1491 break;
1492 }
1493 case MessageQueue::REFRESH: {
1494 handleMessageRefresh();
1495 break;
1496 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001497 }
1498}
1499
Dan Stoza6b9454d2014-11-07 16:00:59 -08001500bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001501 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001502 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001503 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001505 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001506 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001507}
1508
Dan Stoza6b9454d2014-11-07 16:00:59 -08001509bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001510 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512}
1513
1514void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001515 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001516
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001517 mRefreshPending = false;
1518
Pablo Ceballos40845df2016-01-25 17:41:15 -08001519 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001520
Brian Andersond6927fb2016-07-23 23:37:30 -07001521 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001522 rebuildLayerStacks();
1523 setUpHWComposer();
1524 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001525 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001526 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001527 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001528
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001529 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001530
1531 mHadClientComposition = false;
1532 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1533 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1534 mHadClientComposition = mHadClientComposition ||
1535 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1536 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001537
Dan Stoza9e56aa02015-11-02 13:00:03 -08001538 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001539}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001540
Mathias Agopiancd60f992012-08-16 16:28:27 -07001541void SurfaceFlinger::doDebugFlashRegions()
1542{
1543 // is debugging enabled
1544 if (CC_LIKELY(!mDebugRegion))
1545 return;
1546
1547 const bool repaintEverything = mRepaintEverything;
1548 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1549 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001550 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001551 // transform the dirty region into this screen's coordinate space
1552 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1553 if (!dirtyRegion.isEmpty()) {
1554 // redraw the whole screen
1555 doComposeSurfaces(hw, Region(hw->bounds()));
1556
1557 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001559 RenderEngine& engine(getRenderEngine());
1560 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1561
Mathias Agopianda27af92012-09-13 18:17:13 -07001562 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001563 }
1564 }
1565 }
1566
1567 postFramebuffer();
1568
1569 if (mDebugRegion > 1) {
1570 usleep(mDebugRegion * 1000);
1571 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001572
Dan Stoza9e56aa02015-11-02 13:00:03 -08001573 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001574 auto& displayDevice = mDisplays[displayId];
1575 if (!displayDevice->isDisplayOn()) {
1576 continue;
1577 }
1578
1579 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001580 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1581 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001582 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001583}
1584
Adrian Roos1e1a1282017-11-01 19:05:31 +01001585void SurfaceFlinger::doTracing(const char* where) {
1586 ATRACE_CALL();
1587 ATRACE_NAME(where);
1588 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001589 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001590 }
1591}
1592
Brian Andersond6927fb2016-07-23 23:37:30 -07001593void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001594{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001595 ATRACE_CALL();
1596 ALOGV("preComposition");
1597
Mathias Agopiancd60f992012-08-16 16:28:27 -07001598 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001599 mDrawingState.traverseInZOrder([&](Layer* layer) {
1600 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001601 needExtraInvalidate = true;
1602 }
Robert Carr2047fae2016-11-28 14:09:09 -08001603 });
1604
Mathias Agopiancd60f992012-08-16 16:28:27 -07001605 if (needExtraInvalidate) {
1606 signalLayerUpdate();
1607 }
1608}
1609
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001610void SurfaceFlinger::updateCompositorTiming(
1611 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1612 std::shared_ptr<FenceTime>& presentFenceTime) {
1613 // Update queue of past composite+present times and determine the
1614 // most recently known composite to present latency.
1615 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1616 nsecs_t compositeToPresentLatency = -1;
1617 while (!mCompositePresentTimes.empty()) {
1618 CompositePresentTime& cpt = mCompositePresentTimes.front();
1619 // Cached values should have been updated before calling this method,
1620 // which helps avoid duplicate syscalls.
1621 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1622 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1623 break;
1624 }
1625 compositeToPresentLatency = displayTime - cpt.composite;
1626 mCompositePresentTimes.pop();
1627 }
1628
1629 // Don't let mCompositePresentTimes grow unbounded, just in case.
1630 while (mCompositePresentTimes.size() > 16) {
1631 mCompositePresentTimes.pop();
1632 }
1633
Brian Andersond0010582017-03-07 13:20:31 -08001634 setCompositorTimingSnapped(
1635 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1636}
1637
1638void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1639 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001640 // Integer division and modulo round toward 0 not -inf, so we need to
1641 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001642 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001643 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1644 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1645
Brian Andersond0010582017-03-07 13:20:31 -08001646 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1647 if (idealLatency <= 0) {
1648 idealLatency = vsyncInterval;
1649 }
1650
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001651 // Snap the latency to a value that removes scheduling jitter from the
1652 // composition and present times, which often have >1ms of jitter.
1653 // Reducing jitter is important if an app attempts to extrapolate
1654 // something (such as user input) to an accurate diasplay time.
1655 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1656 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001657 nsecs_t bias = vsyncInterval / 2;
1658 int64_t extraVsyncs =
1659 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1660 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1661 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001662
Brian Andersond0010582017-03-07 13:20:31 -08001663 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001664 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1665 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001666 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001667}
1668
1669void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001670{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001671 ATRACE_CALL();
1672 ALOGV("postComposition");
1673
Brian Anderson3546a3f2016-07-14 11:51:14 -07001674 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001675 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001676 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001677 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001678 }
1679
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001680 // |mStateLock| not needed as we are on the main thread
1681 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001682
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001683 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001684 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1685 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1686 glCompositionDoneFenceTime =
1687 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1688 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1689 } else {
1690 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1691 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001692
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001693 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001694 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1695 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1696 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001697
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001698 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1699 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1700
1701 // We use the refreshStartTime which might be sampled a little later than
1702 // when we started doing work for this frame, but that should be okay
1703 // since updateCompositorTiming has snapping logic.
1704 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001705 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001706 CompositorTiming compositorTiming;
1707 {
1708 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1709 compositorTiming = mCompositorTiming;
1710 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001711
Robert Carr2047fae2016-11-28 14:09:09 -08001712 mDrawingState.traverseInZOrder([&](Layer* layer) {
1713 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001714 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001715 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001716 recordBufferingStats(layer->getName().string(),
1717 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001718 }
Robert Carr2047fae2016-11-28 14:09:09 -08001719 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001720
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001721 if (presentFenceTime->isValid()) {
1722 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001723 enableHardwareVsync();
1724 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001725 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001726 }
1727 }
1728
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001729 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001730 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001731 enableHardwareVsync();
1732 }
1733 }
1734
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001735 if (mAnimCompositionPending) {
1736 mAnimCompositionPending = false;
1737
Brian Anderson4e606e32017-03-16 15:34:57 -07001738 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001739 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001740 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001741 } else {
1742 // The HWC doesn't support present fences, so use the refresh
1743 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001744 nsecs_t presentTime =
1745 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001746 mAnimFrameTracker.setActualPresentTime(presentTime);
1747 }
1748 mAnimFrameTracker.advanceFrame();
1749 }
Dan Stozab90cf072015-03-05 11:05:59 -08001750
1751 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1752 return;
1753 }
1754
1755 nsecs_t currentTime = systemTime();
1756 if (mHasPoweredOff) {
1757 mHasPoweredOff = false;
1758 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001759 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001760 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001761 if (numPeriods < NUM_BUCKETS - 1) {
1762 mFrameBuckets[numPeriods] += elapsedTime;
1763 } else {
1764 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1765 }
1766 mTotalTime += elapsedTime;
1767 }
1768 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001769}
1770
1771void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001772 ATRACE_CALL();
1773 ALOGV("rebuildLayerStacks");
1774
Mathias Agopiancd60f992012-08-16 16:28:27 -07001775 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001776 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001777 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001778 mVisibleRegionsDirty = false;
1779 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001780
Jeff Sharkey76488112017-02-27 14:15:18 -07001781 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1782 Region opaqueRegion;
1783 Region dirtyRegion;
1784 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001785 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001786 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1787 const Transform& tr(displayDevice->getTransform());
1788 const Rect bounds(displayDevice->getBounds());
1789 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001790 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001791
Jeff Sharkey76488112017-02-27 14:15:18 -07001792 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001793 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001794 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1795 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001796 Region drawRegion(tr.transform(
1797 layer->visibleNonTransparentRegion));
1798 drawRegion.andSelf(bounds);
1799 if (!drawRegion.isEmpty()) {
1800 layersSortedByZ.add(layer);
1801 } else {
1802 // Clear out the HWC layer if this layer was
1803 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001804 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001805 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001806 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001807 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001808 // WM changes displayDevice->layerStack upon sleep/awake.
1809 // Here we make sure we delete the HWC layers even if
1810 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001811 hwcLayerDestroyed = layer->destroyHwcLayer(
1812 displayDevice->getHwcDisplayId());
1813 }
1814
1815 // If a layer is not going to get a release fence because
1816 // it is invisible, but it is also going to release its
1817 // old buffer, add it to the list of layers needing
1818 // fences.
1819 if (hwcLayerDestroyed) {
1820 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1821 mLayersWithQueuedFrames.cend(), layer);
1822 if (found != mLayersWithQueuedFrames.cend()) {
1823 layersNeedingFences.add(layer);
1824 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001825 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001826 });
1827 }
1828 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001829 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001830 displayDevice->undefinedRegion.set(bounds);
1831 displayDevice->undefinedRegion.subtractSelf(
1832 tr.transform(opaqueRegion));
1833 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001834 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001835 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001836}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001837
Romain Guy0147a172017-06-01 13:53:56 -07001838mat4 SurfaceFlinger::computeSaturationMatrix() const {
1839 if (mSaturation == 1.0f) {
1840 return mat4();
1841 }
1842
1843 // Rec.709 luma coefficients
1844 float3 luminance{0.213f, 0.715f, 0.072f};
1845 luminance *= 1.0f - mSaturation;
1846 return mat4(
1847 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1848 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1849 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1850 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1851 );
1852}
1853
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001854// pickColorMode translates a given dataspace into the best available color mode.
1855// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001856android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001857 if (mForceNativeColorMode) {
1858 return HAL_COLOR_MODE_NATIVE;
1859 }
1860
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001861 switch (dataSpace) {
1862 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1863 // system expects.
1864 case HAL_DATASPACE_UNKNOWN:
1865 case HAL_DATASPACE_SRGB:
1866 case HAL_DATASPACE_V0_SRGB:
1867 return HAL_COLOR_MODE_SRGB;
1868 break;
1869
1870 case HAL_DATASPACE_DISPLAY_P3:
1871 return HAL_COLOR_MODE_DISPLAY_P3;
1872 break;
1873
1874 default:
1875 // TODO (courtneygo): Do we want to assert an error here?
1876 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1877 dataSpace);
1878 return HAL_COLOR_MODE_SRGB;
1879 break;
1880 }
1881}
1882
Romain Guy0147a172017-06-01 13:53:56 -07001883android_dataspace SurfaceFlinger::bestTargetDataSpace(
1884 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001885 // Only support sRGB and Display-P3 right now.
1886 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1887 return HAL_DATASPACE_DISPLAY_P3;
1888 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001889 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1890 return HAL_DATASPACE_DISPLAY_P3;
1891 }
1892 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1893 return HAL_DATASPACE_DISPLAY_P3;
1894 }
1895
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001896 return HAL_DATASPACE_V0_SRGB;
1897}
1898
Mathias Agopiancd60f992012-08-16 16:28:27 -07001899void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001900 ATRACE_CALL();
1901 ALOGV("setUpHWComposer");
1902
Jesse Hall028dc8f2013-08-20 16:35:32 -07001903 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001904 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1905 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1906 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1907
1908 // If nothing has changed (!dirty), don't recompose.
1909 // If something changed, but we don't currently have any visible layers,
1910 // and didn't when we last did a composition, then skip it this time.
1911 // The second rule does two things:
1912 // - When all layers are removed from a display, we'll emit one black
1913 // frame, then nothing more until we get new layers.
1914 // - When a display is created with a private layer stack, we won't
1915 // emit any black frames until a layer is added to the layer stack.
1916 bool mustRecompose = dirty && !(empty && wasEmpty);
1917
1918 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1919 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1920 mustRecompose ? "doing" : "skipping",
1921 dirty ? "+" : "-",
1922 empty ? "+" : "-",
1923 wasEmpty ? "+" : "-");
1924
Dan Stoza71433162014-02-04 16:22:36 -08001925 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001926
1927 if (mustRecompose) {
1928 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1929 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001930 }
1931
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932 // build the h/w work list
1933 if (CC_UNLIKELY(mGeometryInvalid)) {
1934 mGeometryInvalid = false;
1935 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1936 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1937 const auto hwcId = displayDevice->getHwcDisplayId();
1938 if (hwcId >= 0) {
1939 const Vector<sp<Layer>>& currentLayers(
1940 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001941 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001942 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001943 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001944 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001945 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001947 }
1948 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001949
Robert Carrae060832016-11-28 10:51:00 -08001950 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001951 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001952 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001953 }
1954 }
1955 }
1956 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957 }
Riley Andrews03414a12014-07-01 14:22:59 -07001958
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001959
Romain Guy0147a172017-06-01 13:53:56 -07001960 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001961
Dan Stoza9e56aa02015-11-02 13:00:03 -08001962 // Set the per-frame data
1963 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1964 auto& displayDevice = mDisplays[displayId];
1965 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001966
Dan Stoza9e56aa02015-11-02 13:00:03 -08001967 if (hwcId < 0) {
1968 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001969 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001970 if (colorMatrix != mPreviousColorMatrix) {
1971 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1972 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1973 "display %zd: %d", displayId, result);
1974 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001975 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
chaviwc9232ed2017-11-14 15:31:15 -08001976 if (layer->getForceClientComposition(hwcId)) {
1977 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1978 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1979 continue;
1980 }
1981
Dan Stoza9e56aa02015-11-02 13:00:03 -08001982 layer->setPerFrameData(displayDevice);
1983 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001984
1985 if (hasWideColorDisplay) {
1986 android_color_mode newColorMode;
1987 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1988
1989 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1990 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1991 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1992 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1993 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1994 }
1995 newColorMode = pickColorMode(newDataSpace);
1996
Thierry Strudel2924d012017-08-14 15:19:37 -07001997 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001998 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001999 }
2000
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002001 mPreviousColorMatrix = colorMatrix;
2002
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002004 auto& displayDevice = mDisplays[displayId];
2005 if (!displayDevice->isDisplayOn()) {
2006 continue;
2007 }
2008
2009 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002010 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2011 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002012 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002013}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002014
Mathias Agopiancd60f992012-08-16 16:28:27 -07002015void SurfaceFlinger::doComposition() {
2016 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 ALOGV("doComposition");
2018
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002019 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002020 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002021 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002022 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002023 // transform the dirty region into this screen's coordinate space
2024 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002025
2026 // repaint the framebuffer (if needed)
2027 doDisplayComposition(hw, dirtyRegion);
2028
Mathias Agopiancd60f992012-08-16 16:28:27 -07002029 hw->dirtyRegion.clear();
2030 hw->flip(hw->swapRegion);
2031 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07002032 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002033 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002034 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002035}
2036
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002037void SurfaceFlinger::postFramebuffer()
2038{
Mathias Agopian841cde52012-03-01 15:44:37 -08002039 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002041
Mathias Agopiana44b0412011-10-16 18:46:35 -07002042 const nsecs_t now = systemTime();
2043 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002044
Dan Stoza9e56aa02015-11-02 13:00:03 -08002045 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2046 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002047 if (!displayDevice->isDisplayOn()) {
2048 continue;
2049 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 const auto hwcId = displayDevice->getHwcDisplayId();
2051 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002052 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002053 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002054 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002055 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002056 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002057 // The layer buffer from the previous frame (if any) is released
2058 // by HWC only when the release fence from this frame (if any) is
2059 // signaled. Always get the release fence from HWC first.
2060 auto hwcLayer = layer->getHwcLayer(hwcId);
2061 sp<Fence> releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2062
2063 // If the layer was client composited in the previous frame, we
2064 // need to merge with the previous client target acquire fence.
2065 // Since we do not track that, always merge with the current
2066 // client target acquire fence when it is available, even though
2067 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002068 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002069 releaseFence = Fence::merge("LayerRelease", releaseFence,
2070 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002071 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002072
Dan Stoza9e56aa02015-11-02 13:00:03 -08002073 layer->onLayerDisplayed(releaseFence);
2074 }
Chia-I Wu83806892017-11-16 10:50:20 -08002075
2076 // We've got a list of layers needing fences, that are disjoint with
2077 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2078 // supply them with the present fence.
2079 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
2080 sp<Fence> presentFence = mHwc->getPresentFence(hwcId);
2081 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2082 layer->onLayerDisplayed(presentFence);
2083 }
2084 }
2085
Dan Stoza9e56aa02015-11-02 13:00:03 -08002086 if (hwcId >= 0) {
2087 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002088 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002089 }
2090
Mathias Agopiana44b0412011-10-16 18:46:35 -07002091 mLastSwapBufferTime = systemTime() - now;
2092 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002093
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002094 // |mStateLock| not needed as we are on the main thread
2095 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002096 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2097 logFrameStats();
2098 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002099}
2100
Mathias Agopian87baae12012-07-31 12:38:26 -07002101void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002102{
Mathias Agopian841cde52012-03-01 15:44:37 -08002103 ATRACE_CALL();
2104
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002105 // here we keep a copy of the drawing state (that is the state that's
2106 // going to be overwritten by handleTransactionLocked()) outside of
2107 // mStateLock so that the side-effects of the State assignment
2108 // don't happen with mStateLock held (which can cause deadlocks).
2109 State drawingState(mDrawingState);
2110
Mathias Agopianca4d3602011-05-19 15:38:14 -07002111 Mutex::Autolock _l(mStateLock);
2112 const nsecs_t now = systemTime();
2113 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114
Mathias Agopianca4d3602011-05-19 15:38:14 -07002115 // Here we're guaranteed that some transaction flags are set
2116 // so we can call handleTransactionLocked() unconditionally.
2117 // We call getTransactionFlags(), which will also clear the flags,
2118 // with mStateLock held to guarantee that mCurrentState won't change
2119 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002120
Mathias Agopiane57f2922012-08-09 16:29:12 -07002121 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002122 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002123
Mathias Agopianca4d3602011-05-19 15:38:14 -07002124 mLastTransactionTime = systemTime() - now;
2125 mDebugInTransaction = 0;
2126 invalidateHwcGeometry();
2127 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002128}
2129
Mathias Agopian87baae12012-07-31 12:38:26 -07002130void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002131{
Dan Stoza7dde5992015-05-22 09:51:44 -07002132 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002133 mCurrentState.traverseInZOrder([](Layer* layer) {
2134 layer->notifyAvailableFrames();
2135 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002136
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002137 /*
2138 * Traversal of the children
2139 * (perform the transaction for each of them if needed)
2140 */
2141
Mathias Agopian3559b072012-08-15 13:46:03 -07002142 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002143 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002144 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002145 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002146
2147 const uint32_t flags = layer->doTransaction(0);
2148 if (flags & Layer::eVisibleRegion)
2149 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002150 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002151 }
2152
2153 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002154 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002155 */
2156
Mathias Agopiane57f2922012-08-09 16:29:12 -07002157 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002158 // here we take advantage of Vector's copy-on-write semantics to
2159 // improve performance by skipping the transaction entirely when
2160 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002161 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2162 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002163 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002164 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002165 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002166 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002167
2168 // find the displays that were removed
2169 // (ie: in drawing state but not in current state)
2170 // also handle displays that changed
2171 // (ie: displays that are in both lists)
2172 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002173 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2174 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002175 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002176 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002177 // Call makeCurrent() on the primary display so we can
2178 // be sure that nothing associated with this display
2179 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002180 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002181 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002182 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002183 if (hw != NULL)
2184 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002185 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002186 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002187 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002188 } else {
2189 ALOGW("trying to remove the main display");
2190 }
2191 } else {
2192 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002193 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002194 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002195 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2196 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002197 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002198 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002199 // recreating the DisplayDevice, so we just remove it
2200 // from the drawing state, so that it get re-added
2201 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002202 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002203 if (hw != NULL)
2204 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002205 mDisplays.removeItem(display);
2206 mDrawingState.displays.removeItemsAt(i);
2207 dc--; i--;
2208 // at this point we must loop to the next item
2209 continue;
2210 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002211
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002212 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002213 if (disp != NULL) {
2214 if (state.layerStack != draw[i].layerStack) {
2215 disp->setLayerStack(state.layerStack);
2216 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002217 if ((state.orientation != draw[i].orientation)
2218 || (state.viewport != draw[i].viewport)
2219 || (state.frame != draw[i].frame))
2220 {
2221 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002222 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002223 }
Michael Lentine47e45402014-07-18 15:34:25 -07002224 if (state.width != draw[i].width || state.height != draw[i].height) {
2225 disp->setDisplaySize(state.width, state.height);
2226 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002227 }
2228 }
2229 }
2230
2231 // find displays that were added
2232 // (ie: in current state but not in drawing state)
2233 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002234 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002235 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002236
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002237 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002238 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002239 sp<IGraphicBufferProducer> bqProducer;
2240 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002241 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002242
Dan Stoza9e56aa02015-11-02 13:00:03 -08002243 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002244 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002245 // Virtual displays without a surface are dormant:
2246 // they have external state (layer stack, projection,
2247 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002248 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002249
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002250 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002251 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002252 int width = 0;
2253 int status = state.surface->query(
2254 NATIVE_WINDOW_WIDTH, &width);
2255 ALOGE_IF(status != NO_ERROR,
2256 "Unable to query width (%d)", status);
2257 int height = 0;
2258 status = state.surface->query(
2259 NATIVE_WINDOW_HEIGHT, &height);
2260 ALOGE_IF(status != NO_ERROR,
2261 "Unable to query height (%d)", status);
2262 int intFormat = 0;
2263 status = state.surface->query(
2264 NATIVE_WINDOW_FORMAT, &intFormat);
2265 ALOGE_IF(status != NO_ERROR,
2266 "Unable to query format (%d)", status);
2267 auto format = static_cast<android_pixel_format_t>(
2268 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002269
Dan Stoza8cf150a2016-08-02 10:27:31 -07002270 mHwc->allocateVirtualDisplay(width, height, &format,
2271 &hwcId);
2272 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002273
Dan Stoza5cf424b2016-05-20 14:02:39 -07002274 // TODO: Plumb requested format back up to consumer
2275
Dan Stoza9e56aa02015-11-02 13:00:03 -08002276 sp<VirtualDisplaySurface> vds =
2277 new VirtualDisplaySurface(*mHwc,
2278 hwcId, state.surface, bqProducer,
2279 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002280
2281 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002282 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002283 }
2284 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002285 ALOGE_IF(state.surface!=NULL,
2286 "adding a supported display, but rendering "
2287 "surface is provided (%p), ignoring it",
2288 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002289
2290 hwcId = state.type;
2291 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2292 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002293 }
2294
2295 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002296 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002297 sp<DisplayDevice> hw =
2298 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2299 dispSurface, producer,
2300 mRenderEngine->getEGLConfig(),
2301 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002302 hw->setLayerStack(state.layerStack);
2303 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002304 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002305 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002306 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002307 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002308 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002309 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002310 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002311 }
2312 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002314 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002315
Mathias Agopian84300952012-11-21 16:02:13 -08002316 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2317 // The transform hint might have changed for some layers
2318 // (either because a display has changed, or because a layer
2319 // as changed).
2320 //
2321 // Walk through all the layers in currentLayers,
2322 // and update their transform hint.
2323 //
2324 // If a layer is visible only on a single display, then that
2325 // display is used to calculate the hint, otherwise we use the
2326 // default display.
2327 //
2328 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2329 // the hint is set before we acquire a buffer from the surface texture.
2330 //
2331 // NOTE: layer transactions have taken place already, so we use their
2332 // drawing state. However, SurfaceFlinger's own transaction has not
2333 // happened yet, so we must use the current state layer list
2334 // (soon to become the drawing state list).
2335 //
2336 sp<const DisplayDevice> disp;
2337 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002338 bool first = true;
2339 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002340 // NOTE: we rely on the fact that layers are sorted by
2341 // layerStack first (so we don't have to traverse the list
2342 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002343 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002344 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002345 currentlayerStack = layerStack;
2346 // figure out if this layerstack is mirrored
2347 // (more than one display) if so, pick the default display,
2348 // if not, pick the only display it's on.
2349 disp.clear();
2350 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2351 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002352 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002353 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002354 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002355 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002356 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002357 break;
2358 }
2359 }
2360 }
2361 }
Chet Haase91d25932013-04-11 15:24:55 -07002362 if (disp == NULL) {
2363 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2364 // redraw after transform hint changes. See bug 8508397.
2365
2366 // could be null when this layer is using a layerStack
2367 // that is not visible on any display. Also can occur at
2368 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002369 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002370 }
Chet Haase91d25932013-04-11 15:24:55 -07002371 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002372
2373 first = false;
2374 });
Mathias Agopian84300952012-11-21 16:02:13 -08002375 }
2376
2377
Mathias Agopian3559b072012-08-15 13:46:03 -07002378 /*
2379 * Perform our own transaction if needed
2380 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002381
2382 if (mLayersAdded) {
2383 mLayersAdded = false;
2384 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002385 mVisibleRegionsDirty = true;
2386 }
2387
2388 // some layers might have been removed, so
2389 // we need to update the regions they're exposing.
2390 if (mLayersRemoved) {
2391 mLayersRemoved = false;
2392 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002393 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002394 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002395 // this layer is not visible anymore
2396 // TODO: we could traverse the tree from front to back and
2397 // compute the actual visible region
2398 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002399 Region visibleReg;
2400 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002401 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002402 }
Robert Carr2047fae2016-11-28 14:09:09 -08002403 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002404 }
2405
2406 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002407
2408 updateCursorAsync();
2409}
2410
2411void SurfaceFlinger::updateCursorAsync()
2412{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002413 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2414 auto& displayDevice = mDisplays[displayId];
2415 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002416 continue;
2417 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002418
2419 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2420 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002421 }
2422 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002423}
2424
2425void SurfaceFlinger::commitTransaction()
2426{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002427 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002428 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002429 for (const auto& l : mLayersPendingRemoval) {
2430 recordBufferingStats(l->getName().string(),
2431 l->getOccupancyHistory(true));
2432 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002433 }
2434 mLayersPendingRemoval.clear();
2435 }
2436
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002437 // If this transaction is part of a window animation then the next frame
2438 // we composite should be considered an animation as well.
2439 mAnimCompositionPending = mAnimTransactionPending;
2440
Mathias Agopian4fec8732012-06-29 14:12:52 -07002441 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002442 mDrawingState.traverseInZOrder([](Layer* layer) {
2443 layer->commitChildList();
2444 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002445 mTransactionPending = false;
2446 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002447 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002448}
2449
Chia-I Wuab0c3192017-08-01 11:29:00 -07002450void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002451 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452{
Mathias Agopian841cde52012-03-01 15:44:37 -08002453 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002454 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002455
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456 Region aboveOpaqueLayers;
2457 Region aboveCoveredLayers;
2458 Region dirty;
2459
Mathias Agopian87baae12012-07-31 12:38:26 -07002460 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002461
Robert Carr2047fae2016-11-28 14:09:09 -08002462 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002464 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465
Jesse Hall01e29052013-02-19 16:13:35 -08002466 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002467 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002468 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002469
Mathias Agopianab028732010-03-16 16:41:46 -07002470 /*
2471 * opaqueRegion: area of a surface that is fully opaque.
2472 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002474
2475 /*
2476 * visibleRegion: area of a surface that is visible on screen
2477 * and not fully transparent. This is essentially the layer's
2478 * footprint minus the opaque regions above it.
2479 * Areas covered by a translucent surface are considered visible.
2480 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002481 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002482
2483 /*
2484 * coveredRegion: area of a surface that is covered by all
2485 * visible regions above it (which includes the translucent areas).
2486 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002488
Jesse Halla8026d22012-09-25 13:25:04 -07002489 /*
2490 * transparentRegion: area of a surface that is hinted to be completely
2491 * transparent. This is only used to tell when the layer has no visible
2492 * non-transparent regions and can be removed from the layer list. It
2493 * does not affect the visibleRegion of this layer or any layers
2494 * beneath it. The hint may not be correct if apps don't respect the
2495 * SurfaceView restrictions (which, sadly, some don't).
2496 */
2497 Region transparentRegion;
2498
Mathias Agopianab028732010-03-16 16:41:46 -07002499
2500 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002501 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002502 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002503 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002505 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002506 if (!visibleRegion.isEmpty()) {
2507 // Remove the transparent area from the visible region
2508 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002509 if (tr.preserveRects()) {
2510 // transform the transparent region
2511 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002512 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002513 // transformation too complex, can't do the
2514 // transparent region optimization.
2515 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002516 }
Mathias Agopianab028732010-03-16 16:41:46 -07002517 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518
Mathias Agopianab028732010-03-16 16:41:46 -07002519 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002520 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002521 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002522 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2523 // the opaque region is the layer's footprint
2524 opaqueRegion = visibleRegion;
2525 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526 }
2527 }
2528
Mathias Agopianab028732010-03-16 16:41:46 -07002529 // Clip the covered region to the visible region
2530 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2531
2532 // Update aboveCoveredLayers for next (lower) layer
2533 aboveCoveredLayers.orSelf(visibleRegion);
2534
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002535 // subtract the opaque region covered by the layers above us
2536 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002537
2538 // compute this layer's dirty region
2539 if (layer->contentDirty) {
2540 // we need to invalidate the whole region
2541 dirty = visibleRegion;
2542 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002543 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002544 layer->contentDirty = false;
2545 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002546 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002547 * the exposed region consists of two components:
2548 * 1) what's VISIBLE now and was COVERED before
2549 * 2) what's EXPOSED now less what was EXPOSED before
2550 *
2551 * note that (1) is conservative, we start with the whole
2552 * visible region but only keep what used to be covered by
2553 * something -- which mean it may have been exposed.
2554 *
2555 * (2) handles areas that were not covered by anything but got
2556 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002557 */
Mathias Agopianab028732010-03-16 16:41:46 -07002558 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002559 const Region oldVisibleRegion = layer->visibleRegion;
2560 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002561 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2562 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563 }
2564 dirty.subtractSelf(aboveOpaqueLayers);
2565
2566 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002567 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568
Mathias Agopianab028732010-03-16 16:41:46 -07002569 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002570 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002571
Jesse Halla8026d22012-09-25 13:25:04 -07002572 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573 layer->setVisibleRegion(visibleRegion);
2574 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002575 layer->setVisibleNonTransparentRegion(
2576 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002577 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578
Mathias Agopian87baae12012-07-31 12:38:26 -07002579 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580}
2581
Chia-I Wuab0c3192017-08-01 11:29:00 -07002582void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002583 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002584 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002585 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002586 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002587 }
2588 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002589}
2590
Dan Stoza6b9454d2014-11-07 16:00:59 -08002591bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002593 ALOGV("handlePageFlip");
2594
Brian Andersond6927fb2016-07-23 23:37:30 -07002595 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596
Mathias Agopian4fec8732012-06-29 14:12:52 -07002597 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002598 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002599 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002600
2601 // Store the set of layers that need updates. This set must not change as
2602 // buffers are being latched, as this could result in a deadlock.
2603 // Example: Two producers share the same command stream and:
2604 // 1.) Layer 0 is latched
2605 // 2.) Layer 0 gets a new frame
2606 // 2.) Layer 1 gets a new frame
2607 // 3.) Layer 1 is latched.
2608 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2609 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002610 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002611 if (layer->hasQueuedFrame()) {
2612 frameQueued = true;
2613 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002614 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002615 } else {
2616 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002617 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002618 } else {
2619 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002620 }
Robert Carr2047fae2016-11-28 14:09:09 -08002621 });
2622
Dan Stoza9e56aa02015-11-02 13:00:03 -08002623 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002624 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002625 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002626 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002627 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002628 newDataLatched = true;
2629 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002630 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002631
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002632 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002633
2634 // If we will need to wake up at some time in the future to deal with a
2635 // queued frame that shouldn't be displayed during this vsync period, wake
2636 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002637 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002638 signalLayerUpdate();
2639 }
2640
2641 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002642 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643}
2644
Mathias Agopianad456f92011-01-13 17:53:01 -08002645void SurfaceFlinger::invalidateHwcGeometry()
2646{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002647 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002648}
2649
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002650
Fabien Sanglard830b8472016-11-30 16:35:58 -08002651void SurfaceFlinger::doDisplayComposition(
2652 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002653 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654{
Dan Stoza71433162014-02-04 16:22:36 -08002655 // We only need to actually compose the display if:
2656 // 1) It is being handled by hardware composer, which may need this to
2657 // keep its virtual display state machine in sync, or
2658 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002659 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002660 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002661 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002662 return;
2663 }
2664
Dan Stoza9e56aa02015-11-02 13:00:03 -08002665 ALOGV("doDisplayComposition");
2666
Mathias Agopian87baae12012-07-31 12:38:26 -07002667 Region dirtyRegion(inDirtyRegion);
2668
Mathias Agopianb8a55602009-06-26 19:06:36 -07002669 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002670 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002671
Fabien Sanglard830b8472016-11-30 16:35:58 -08002672 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002673 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002674 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2675 // takes a rectangle, we must make sure to update that whole
2676 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002677 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002678 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002679 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002680 // We need to redraw the rectangle that will be updated
2681 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002682 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002683 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002684 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002685 } else {
2686 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002687 dirtyRegion.set(displayDevice->bounds());
2688 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689 }
2690 }
2691
Fabien Sanglard830b8472016-11-30 16:35:58 -08002692 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002693
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002694 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002695 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002696
2697 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002698 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699}
2700
Dan Stoza9e56aa02015-11-02 13:00:03 -08002701bool SurfaceFlinger::doComposeSurfaces(
2702 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002703{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002704 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002705
chaviwa76b2712017-09-20 12:02:26 -07002706 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002707 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002708
2709 mat4 oldColorMatrix;
2710 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2711 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2712 if (applyColorMatrix) {
2713 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2714 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2715 }
2716
Dan Stoza9e56aa02015-11-02 13:00:03 -08002717 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2718 if (hasClientComposition) {
2719 ALOGV("hasClientComposition");
2720
Romain Guy54f154a2017-10-24 21:40:32 +01002721 mRenderEngine->setWideColor(
2722 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2723 mRenderEngine->setColorMode(mForceNativeColorMode ?
2724 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002725 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002726 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002727 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002728 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002729
2730 // |mStateLock| not needed as we are on the main thread
2731 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002732 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2733 }
2734 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002735 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002736
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002737 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002738 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2739 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002740 // when using overlays, we assume a fully transparent framebuffer
2741 // NOTE: we could reduce how much we need to clear, for instance
2742 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002743 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002744 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002745 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002746 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002747 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002748 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002749
2750 // we remove the scissor part
2751 // we're left with the letterbox region
2752 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002753 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002754
2755 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002756 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002757
2758 // but limit it to the dirty region
2759 region.andSelf(dirty);
2760
Mathias Agopianb9494d52012-04-18 02:28:45 -07002761 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002762 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002763 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002764 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002765 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002766 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002767
Dan Stoza9e56aa02015-11-02 13:00:03 -08002768 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002769 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002770 // scissor on the main display. It should never be needed
2771 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002772 const Rect& bounds(displayDevice->getBounds());
2773 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002774 if (scissor != bounds) {
2775 // scissor doesn't match the screen's dimensions, so we
2776 // need to clear everything outside of it and enable
2777 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002778
Mathias Agopianf45c5102012-10-24 16:29:17 -07002779 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002780 const uint32_t height = displayDevice->getHeight();
2781 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002782 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002783 }
2784 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002785 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002786
Mathias Agopian85d751c2012-08-29 16:59:24 -07002787 /*
2788 * and then, render the layers targeted at the framebuffer
2789 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002790
Dan Stoza9e56aa02015-11-02 13:00:03 -08002791 ALOGV("Rendering client layers");
2792 const Transform& displayTransform = displayDevice->getTransform();
2793 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002794 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002795 bool firstLayer = true;
2796 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2797 const Region clip(dirty.intersect(
2798 displayTransform.transform(layer->visibleRegion)));
2799 ALOGV("Layer: %s", layer->getName().string());
2800 ALOGV(" Composition type: %s",
2801 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002802 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002803 switch (layer->getCompositionType(hwcId)) {
2804 case HWC2::Composition::Cursor:
2805 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002806 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002807 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002808 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002809 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002810 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002811 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002812 // never clear the very first layer since we're
2813 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002814 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002815 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002816 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002817 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002818 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002819 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002820 break;
2821 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002822 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002823 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002824 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002825 } else {
2826 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002827 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002828 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002829 }
2830 } else {
2831 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002832 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002833 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002834 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002835 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002836 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002837 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002838 }
2839 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002840
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002841 if (applyColorMatrix) {
2842 getRenderEngine().setupColorTransform(oldColorMatrix);
2843 }
2844
Mathias Agopianf45c5102012-10-24 16:29:17 -07002845 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002846 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002847 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848}
2849
Fabien Sanglard830b8472016-11-30 16:35:58 -08002850void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2851 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002852 RenderEngine& engine(getRenderEngine());
2853 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854}
2855
Dan Stoza7d89d062015-04-30 13:29:25 -07002856status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002857 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002858 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002859 const sp<Layer>& lbc,
2860 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002861{
Dan Stoza7d89d062015-04-30 13:29:25 -07002862 // add this layer to the current state list
2863 {
2864 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002865 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002866 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2867 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002868 return NO_MEMORY;
2869 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002870 if (parent == nullptr) {
2871 mCurrentState.layersSortedByZ.add(lbc);
2872 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002873 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002874 ALOGE("addClientLayer called with a removed parent");
2875 return NAME_NOT_FOUND;
2876 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002877 parent->addChild(lbc);
2878 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002879
Dan Stoza7d89d062015-04-30 13:29:25 -07002880 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002881 mLayersAdded = true;
2882 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002883 }
2884
Mathias Agopian96f08192010-06-02 23:28:45 -07002885 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002886 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002887
Dan Stoza7d89d062015-04-30 13:29:25 -07002888 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002889}
2890
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002891status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002892 Mutex::Autolock _l(mStateLock);
2893
chaviw8b3871a2017-11-01 17:41:01 -07002894 if (layer->isPendingRemoval()) {
2895 return NO_ERROR;
2896 }
2897
Robert Carr1f0a16a2016-10-24 16:27:39 -07002898 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002899 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002900 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002901 if (topLevelOnly) {
2902 return NO_ERROR;
2903 }
2904
Chia-I Wu98f1c102017-05-30 14:54:08 -07002905 sp<Layer> ancestor = p;
2906 while (ancestor->getParent() != nullptr) {
2907 ancestor = ancestor->getParent();
2908 }
2909 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2910 ALOGE("removeLayer called with a layer whose parent has been removed");
2911 return NAME_NOT_FOUND;
2912 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002913
2914 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002915 } else {
2916 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002917 }
2918
Robert Carr136e2f62017-02-08 17:54:29 -08002919 // As a matter of normal operation, the LayerCleaner will produce a second
2920 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2921 // so we will succeed in promoting it, but it's already been removed
2922 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2923 // otherwise something has gone wrong and we are leaking the layer.
2924 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002925 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2926 layer->getName().string(),
2927 (p != nullptr) ? p->getName().string() : "no-parent");
2928 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002929 } else if (index < 0) {
2930 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002931 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002932
Chia-I Wuc6657022017-08-15 11:18:17 -07002933 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002934 mLayersPendingRemoval.add(layer);
2935 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002936 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002937 setTransactionFlags(eTransactionNeeded);
2938 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002939}
2940
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002941uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002942 return android_atomic_release_load(&mTransactionFlags);
2943}
2944
Mathias Agopian3f844832013-08-07 21:24:32 -07002945uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002946 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2947}
2948
Mathias Agopian3f844832013-08-07 21:24:32 -07002949uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002950 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2951 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002952 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002953 }
2954 return old;
2955}
2956
Mathias Agopian8b33f032012-07-24 20:43:54 -07002957void SurfaceFlinger::setTransactionState(
2958 const Vector<ComposerState>& state,
2959 const Vector<DisplayState>& displays,
2960 uint32_t flags)
2961{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002962 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002963 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002964 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002965
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002966 if (flags & eAnimation) {
2967 // For window updates that are part of an animation we must wait for
2968 // previous animation "frames" to be handled.
2969 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002970 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002971 if (CC_UNLIKELY(err != NO_ERROR)) {
2972 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002973 // caller after a few seconds.
2974 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2975 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002976 mAnimTransactionPending = false;
2977 break;
2978 }
2979 }
2980 }
2981
Mathias Agopiane57f2922012-08-09 16:29:12 -07002982 size_t count = displays.size();
2983 for (size_t i=0 ; i<count ; i++) {
2984 const DisplayState& s(displays[i]);
2985 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002986 }
2987
Mathias Agopiane57f2922012-08-09 16:29:12 -07002988 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002989 for (size_t i=0 ; i<count ; i++) {
2990 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002991 // Here we need to check that the interface we're given is indeed
2992 // one of our own. A malicious client could give us a NULL
2993 // IInterface, or one of its own or even one of our own but a
2994 // different type. All these situations would cause us to crash.
2995 //
2996 // NOTE: it would be better to use RTTI as we could directly check
2997 // that we have a Client*. however, RTTI is disabled in Android.
2998 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002999 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003000 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08003001 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003002 sp<Client> client( static_cast<Client *>(s.client.get()) );
3003 transactionFlags |= setClientStateLocked(client, s.state);
3004 }
3005 }
3006 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003007 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003008
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003009 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3010 // anyway. This can be used as a flush mechanism for previous async transactions.
3011 // Empty animation transaction can be used to simulate back-pressure, so also force a
3012 // transaction for empty animation transactions.
3013 if (transactionFlags == 0 &&
3014 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003015 transactionFlags = eTransactionNeeded;
3016 }
3017
Mathias Agopian386aa982011-11-07 21:58:03 -08003018 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003019 if (mInterceptor.isEnabled()) {
3020 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
3021 }
Irvel468051e2016-06-13 16:44:44 -07003022
Mathias Agopian386aa982011-11-07 21:58:03 -08003023 // this triggers the transaction
3024 setTransactionFlags(transactionFlags);
3025
3026 // if this is a synchronous transaction, wait for it to take effect
3027 // before returning.
3028 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003029 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003030 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003031 if (flags & eAnimation) {
3032 mAnimTransactionPending = true;
3033 }
3034 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003035 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3036 if (CC_UNLIKELY(err != NO_ERROR)) {
3037 // just in case something goes wrong in SF, return to the
3038 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003039 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3040 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003041 break;
3042 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003043 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003044 }
3045}
3046
Mathias Agopiane57f2922012-08-09 16:29:12 -07003047uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3048{
Jesse Hall9a143922012-10-04 16:29:19 -07003049 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3050 if (dpyIdx < 0)
3051 return 0;
3052
Mathias Agopiane57f2922012-08-09 16:29:12 -07003053 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003054 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003055 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003056 const uint32_t what = s.what;
3057 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003058 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003059 disp.surface = s.surface;
3060 flags |= eDisplayTransactionNeeded;
3061 }
3062 }
3063 if (what & DisplayState::eLayerStackChanged) {
3064 if (disp.layerStack != s.layerStack) {
3065 disp.layerStack = s.layerStack;
3066 flags |= eDisplayTransactionNeeded;
3067 }
3068 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003069 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003070 if (disp.orientation != s.orientation) {
3071 disp.orientation = s.orientation;
3072 flags |= eDisplayTransactionNeeded;
3073 }
3074 if (disp.frame != s.frame) {
3075 disp.frame = s.frame;
3076 flags |= eDisplayTransactionNeeded;
3077 }
3078 if (disp.viewport != s.viewport) {
3079 disp.viewport = s.viewport;
3080 flags |= eDisplayTransactionNeeded;
3081 }
3082 }
Michael Lentine47e45402014-07-18 15:34:25 -07003083 if (what & DisplayState::eDisplaySizeChanged) {
3084 if (disp.width != s.width) {
3085 disp.width = s.width;
3086 flags |= eDisplayTransactionNeeded;
3087 }
3088 if (disp.height != s.height) {
3089 disp.height = s.height;
3090 flags |= eDisplayTransactionNeeded;
3091 }
3092 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003093 }
3094 return flags;
3095}
3096
3097uint32_t SurfaceFlinger::setClientStateLocked(
3098 const sp<Client>& client,
3099 const layer_state_t& s)
3100{
Mathias Agopian13127d82013-03-05 17:47:11 -08003101 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003102 if (layer == nullptr) {
3103 return 0;
3104 }
3105
3106 if (layer->isPendingRemoval()) {
3107 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3108 return 0;
3109 }
3110
3111 uint32_t flags = 0;
3112
3113 const uint32_t what = s.what;
3114 bool geometryAppliesWithResize =
3115 what & layer_state_t::eGeometryAppliesWithResize;
3116 if (what & layer_state_t::ePositionChanged) {
3117 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3118 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003119 }
chaviw8b3871a2017-11-01 17:41:01 -07003120 }
3121 if (what & layer_state_t::eLayerChanged) {
3122 // NOTE: index needs to be calculated before we update the state
3123 const auto& p = layer->getParent();
3124 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003125 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003126 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003127 mCurrentState.layersSortedByZ.removeAt(idx);
3128 mCurrentState.layersSortedByZ.add(layer);
3129 // we need traversal (state changed)
3130 // AND transaction (list changed)
3131 flags |= eTransactionNeeded|eTraversalNeeded;
3132 }
chaviw8b3871a2017-11-01 17:41:01 -07003133 } else {
3134 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003135 flags |= eTransactionNeeded|eTraversalNeeded;
3136 }
3137 }
chaviw8b3871a2017-11-01 17:41:01 -07003138 }
3139 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003140 // NOTE: index needs to be calculated before we update the state
3141 const auto& p = layer->getParent();
3142 if (p == nullptr) {
3143 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3144 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3145 mCurrentState.layersSortedByZ.removeAt(idx);
3146 mCurrentState.layersSortedByZ.add(layer);
3147 // we need traversal (state changed)
3148 // AND transaction (list changed)
3149 flags |= eTransactionNeeded|eTraversalNeeded;
3150 }
3151 } else {
3152 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3153 flags |= eTransactionNeeded|eTraversalNeeded;
3154 }
chaviw8b3871a2017-11-01 17:41:01 -07003155 }
3156 }
3157 if (what & layer_state_t::eSizeChanged) {
3158 if (layer->setSize(s.w, s.h)) {
3159 flags |= eTraversalNeeded;
3160 }
3161 }
3162 if (what & layer_state_t::eAlphaChanged) {
3163 if (layer->setAlpha(s.alpha))
3164 flags |= eTraversalNeeded;
3165 }
3166 if (what & layer_state_t::eColorChanged) {
3167 if (layer->setColor(s.color))
3168 flags |= eTraversalNeeded;
3169 }
3170 if (what & layer_state_t::eMatrixChanged) {
3171 if (layer->setMatrix(s.matrix))
3172 flags |= eTraversalNeeded;
3173 }
3174 if (what & layer_state_t::eTransparentRegionChanged) {
3175 if (layer->setTransparentRegionHint(s.transparentRegion))
3176 flags |= eTraversalNeeded;
3177 }
3178 if (what & layer_state_t::eFlagsChanged) {
3179 if (layer->setFlags(s.flags, s.mask))
3180 flags |= eTraversalNeeded;
3181 }
3182 if (what & layer_state_t::eCropChanged) {
3183 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3184 flags |= eTraversalNeeded;
3185 }
3186 if (what & layer_state_t::eFinalCropChanged) {
3187 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3188 flags |= eTraversalNeeded;
3189 }
3190 if (what & layer_state_t::eLayerStackChanged) {
3191 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3192 // We only allow setting layer stacks for top level layers,
3193 // everything else inherits layer stack from its parent.
3194 if (layer->hasParent()) {
3195 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3196 layer->getName().string());
3197 } else if (idx < 0) {
3198 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3199 "that also does not appear in the top level layer list. Something"
3200 " has gone wrong.", layer->getName().string());
3201 } else if (layer->setLayerStack(s.layerStack)) {
3202 mCurrentState.layersSortedByZ.removeAt(idx);
3203 mCurrentState.layersSortedByZ.add(layer);
3204 // we need traversal (state changed)
3205 // AND transaction (list changed)
3206 flags |= eTransactionNeeded|eTraversalNeeded;
3207 }
3208 }
3209 if (what & layer_state_t::eDeferTransaction) {
3210 if (s.barrierHandle != nullptr) {
3211 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3212 } else if (s.barrierGbp != nullptr) {
3213 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3214 if (authenticateSurfaceTextureLocked(gbp)) {
3215 const auto& otherLayer =
3216 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3217 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3218 } else {
3219 ALOGE("Attempt to defer transaction to to an"
3220 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003221 }
3222 }
chaviw8b3871a2017-11-01 17:41:01 -07003223 // We don't trigger a traversal here because if no other state is
3224 // changed, we don't want this to cause any more work
3225 }
3226 if (what & layer_state_t::eReparent) {
3227 if (layer->reparent(s.parentHandleForChild)) {
3228 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003229 }
chaviw8b3871a2017-11-01 17:41:01 -07003230 }
3231 if (what & layer_state_t::eReparentChildren) {
3232 if (layer->reparentChildren(s.reparentHandle)) {
3233 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003234 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003235 }
chaviw8b3871a2017-11-01 17:41:01 -07003236 if (what & layer_state_t::eDetachChildren) {
3237 layer->detachChildren();
3238 }
3239 if (what & layer_state_t::eOverrideScalingModeChanged) {
3240 layer->setOverrideScalingMode(s.overrideScalingMode);
3241 // We don't trigger a traversal here because if no other state is
3242 // changed, we don't want this to cause any more work
3243 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003244 return flags;
3245}
3246
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003247status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003248 const String8& name,
3249 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003250 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003251 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3252 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003253{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003254 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003255 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003256 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003257 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003258 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003259
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003260 status_t result = NO_ERROR;
3261
3262 sp<Layer> layer;
3263
Cody Northropbc755282017-03-31 12:00:08 -06003264 String8 uniqueName = getUniqueLayerName(name);
3265
Mathias Agopian3165cc22012-08-08 19:42:09 -07003266 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3267 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003268 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003269 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003270 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003271
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003272 break;
chaviw13fdc492017-06-27 12:40:18 -07003273 case ISurfaceComposerClient::eFXSurfaceColor:
3274 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003275 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003276 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003277 break;
3278 default:
3279 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003280 break;
3281 }
3282
Dan Stoza7d89d062015-04-30 13:29:25 -07003283 if (result != NO_ERROR) {
3284 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003285 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003286
Chia-I Wuab0c3192017-08-01 11:29:00 -07003287 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3288 // TODO b/64227542
3289 if (windowType == 441731) {
3290 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3291 layer->setPrimaryDisplayOnly();
3292 }
3293
Albert Chaulk479c60c2017-01-27 14:21:34 -05003294 layer->setInfo(windowType, ownerUid);
3295
Robert Carr1f0a16a2016-10-24 16:27:39 -07003296 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003297 if (result != NO_ERROR) {
3298 return result;
3299 }
Irvelffc9efc2016-07-27 15:16:37 -07003300 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003301
3302 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003303 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003304}
3305
Cody Northropbc755282017-03-31 12:00:08 -06003306String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3307{
3308 bool matchFound = true;
3309 uint32_t dupeCounter = 0;
3310
3311 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3312 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3313
3314 // Loop over layers until we're sure there is no matching name
3315 while (matchFound) {
3316 matchFound = false;
3317 mDrawingState.traverseInZOrder([&](Layer* layer) {
3318 if (layer->getName() == uniqueName) {
3319 matchFound = true;
3320 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3321 }
3322 });
3323 }
3324
3325 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3326
3327 return uniqueName;
3328}
3329
David Sodman0c69cad2017-08-21 12:12:51 -07003330status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003331 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3332 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003333{
3334 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003335 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003336 case PIXEL_FORMAT_TRANSPARENT:
3337 case PIXEL_FORMAT_TRANSLUCENT:
3338 format = PIXEL_FORMAT_RGBA_8888;
3339 break;
3340 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003341 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003342 break;
3343 }
3344
David Sodman0c69cad2017-08-21 12:12:51 -07003345 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3346 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003347 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003348 *handle = layer->getHandle();
3349 *gbp = layer->getProducer();
3350 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003351 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003352
David Sodman0c69cad2017-08-21 12:12:51 -07003353 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003354 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003355}
3356
chaviw13fdc492017-06-27 12:40:18 -07003357status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003358 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003359 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003360{
chaviw13fdc492017-06-27 12:40:18 -07003361 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003362 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003363 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003364}
3365
Mathias Agopianac9fa422013-02-11 16:40:36 -08003366status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003367{
Robert Carr9524cb32017-02-13 11:32:32 -08003368 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003369 status_t err = NO_ERROR;
3370 sp<Layer> l(client->getLayerUser(handle));
3371 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003372 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003373 err = removeLayer(l);
3374 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3375 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003376 }
3377 return err;
3378}
3379
Mathias Agopian13127d82013-03-05 17:47:11 -08003380status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003381{
Mathias Agopian67106042013-03-14 19:18:13 -07003382 // called by ~LayerCleaner() when all references to the IBinder (handle)
3383 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003384 sp<Layer> l = layer.promote();
3385 if (l == nullptr) {
3386 // The layer has already been removed, carry on
3387 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003388 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003389 // If we have a parent, then we can continue to live as long as it does.
3390 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003391}
3392
Mathias Agopianb60314a2012-04-10 22:09:54 -07003393// ---------------------------------------------------------------------------
3394
Andy McFadden13a082e2012-08-24 10:16:42 -07003395void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003396 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003397 Vector<ComposerState> state;
3398 Vector<DisplayState> displays;
3399 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003400 d.what = DisplayState::eDisplayProjectionChanged |
3401 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003402 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003403 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003404 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003405 d.frame.makeInvalid();
3406 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003407 d.width = 0;
3408 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003409 displays.add(d);
3410 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003411 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3412 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003413
Dan Stoza9e56aa02015-11-02 13:00:03 -08003414 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3415 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003416 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003417
Brian Andersond0010582017-03-07 13:20:31 -08003418 // Use phase of 0 since phase is not known.
3419 // Use latency of 0, which will snap to the ideal latency.
3420 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003421}
3422
3423void SurfaceFlinger::initializeDisplays() {
3424 class MessageScreenInitialized : public MessageBase {
3425 SurfaceFlinger* flinger;
3426 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003427 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003428 virtual bool handler() {
3429 flinger->onInitializeDisplays();
3430 return true;
3431 }
3432 };
3433 sp<MessageBase> msg = new MessageScreenInitialized(this);
3434 postMessageAsync(msg); // we may be called from main thread, use async message
3435}
3436
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003437void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003438 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003439 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3440 this);
3441 int32_t type = hw->getDisplayType();
3442 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003443
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003444 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003445 return;
3446 }
3447
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003448 hw->setPowerMode(mode);
3449 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3450 ALOGW("Trying to set power mode for virtual display");
3451 return;
3452 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003453
Irvelffc9efc2016-07-27 15:16:37 -07003454 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003455 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003456 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3457 if (idx < 0) {
3458 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3459 return;
3460 }
3461 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3462 }
3463
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003464 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003465 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003466 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003467 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3468 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003469 // FIXME: eventthread only knows about the main display right now
3470 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003471 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003472 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003473
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003474 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003475 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003476 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003477
3478 struct sched_param param = {0};
3479 param.sched_priority = 1;
3480 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3481 ALOGW("Couldn't set SCHED_FIFO on display on");
3482 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003483 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003484 // Turn off the display
3485 struct sched_param param = {0};
3486 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3487 ALOGW("Couldn't set SCHED_OTHER on display off");
3488 }
3489
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003490 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3491 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003492 disableHardwareVsync(true); // also cancels any in-progress resync
3493
Mathias Agopiancde87a32012-09-13 14:09:01 -07003494 // FIXME: eventthread only knows about the main display right now
3495 mEventThread->onScreenReleased();
3496 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003497
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003498 getHwComposer().setPowerMode(type, mode);
3499 mVisibleRegionsDirty = true;
3500 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003501 } else if (mode == HWC_POWER_MODE_DOZE ||
3502 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003503 // Update display while dozing
3504 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003505 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3506 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003507 // FIXME: eventthread only knows about the main display right now
3508 mEventThread->onScreenAcquired();
3509 resyncToHardwareVsync(true);
3510 }
3511 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3512 // Leave display going to doze
3513 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3514 disableHardwareVsync(true); // also cancels any in-progress resync
3515 // FIXME: eventthread only knows about the main display right now
3516 mEventThread->onScreenReleased();
3517 }
3518 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003519 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003520 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003521 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003522 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003523}
3524
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003525void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3526 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003527 SurfaceFlinger& mFlinger;
3528 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003529 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003530 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003531 MessageSetPowerMode(SurfaceFlinger& flinger,
3532 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3533 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003534 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003535 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003536 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003537 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003538 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003539 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003540 ALOGW("Attempt to set power mode = %d for virtual display",
3541 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003542 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003543 mFlinger.setPowerModeInternal(
3544 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003545 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003546 return true;
3547 }
3548 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003549 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003550 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003551}
3552
3553// ---------------------------------------------------------------------------
3554
Vishnu Nair6a408532017-10-24 09:11:27 -07003555status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003556 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003557
Mathias Agopianbd115332013-04-18 16:41:04 -07003558 IPCThreadState* ipc = IPCThreadState::self();
3559 const int pid = ipc->getCallingPid();
3560 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003561
Mathias Agopianbd115332013-04-18 16:41:04 -07003562 if ((uid != AID_SHELL) &&
3563 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003564 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003565 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003566 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003567 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003568 // (this would indicate SF is stuck, but we want to be able to
3569 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003570 status_t err = mStateLock.timedLock(s2ns(1));
3571 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003572 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003573 result.appendFormat(
3574 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3575 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003576 }
3577
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003578 bool dumpAll = true;
3579 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003580 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003581
3582 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003583 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003584 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3585 dumpAll = false;
3586 }
3587
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003588 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003589 if ((index < numArgs) &&
3590 (args[index] == String16("--list"))) {
3591 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003592 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003593 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003594 }
3595
3596 if ((index < numArgs) &&
3597 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003598 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003599 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003600 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003601 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003602
3603 if ((index < numArgs) &&
3604 (args[index] == String16("--latency-clear"))) {
3605 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003606 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003607 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003608 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003609
3610 if ((index < numArgs) &&
3611 (args[index] == String16("--dispsync"))) {
3612 index++;
3613 mPrimaryDispSync.dump(result);
3614 dumpAll = false;
3615 }
Dan Stozab90cf072015-03-05 11:05:59 -08003616
3617 if ((index < numArgs) &&
3618 (args[index] == String16("--static-screen"))) {
3619 index++;
3620 dumpStaticScreenStats(result);
3621 dumpAll = false;
3622 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003623
3624 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003625 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003626 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003627 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003628 dumpAll = false;
3629 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003630
3631 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3632 index++;
3633 dumpWideColorInfo(result);
3634 dumpAll = false;
3635 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003636 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003637
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003638 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003639 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003640 }
3641
Mathias Agopian9795c422009-08-26 16:36:26 -07003642 if (locked) {
3643 mStateLock.unlock();
3644 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003645 }
3646 write(fd, result.string(), result.size());
3647 return NO_ERROR;
3648}
3649
Dan Stozac7014012014-02-14 15:03:43 -08003650void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3651 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003652{
Robert Carr2047fae2016-11-28 14:09:09 -08003653 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003654 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003655 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003656}
3657
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003658void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003659 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003660{
3661 String8 name;
3662 if (index < args.size()) {
3663 name = String8(args[index]);
3664 index++;
3665 }
3666
Dan Stoza9e56aa02015-11-02 13:00:03 -08003667 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3668 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003669 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003670
3671 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003672 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003673 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003674 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003675 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003676 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003677 }
Robert Carr2047fae2016-11-28 14:09:09 -08003678 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003679 }
3680}
3681
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003682void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003683 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003684{
3685 String8 name;
3686 if (index < args.size()) {
3687 name = String8(args[index]);
3688 index++;
3689 }
3690
Robert Carr2047fae2016-11-28 14:09:09 -08003691 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003692 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003693 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003694 }
Robert Carr2047fae2016-11-28 14:09:09 -08003695 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003696
Svetoslavd85084b2014-03-20 10:28:31 -07003697 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003698}
3699
Jamie Gennis6547ff42013-07-16 20:12:42 -07003700// This should only be called from the main thread. Otherwise it would need
3701// the lock and should use mCurrentState rather than mDrawingState.
3702void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003703 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003704 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003705 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003706
3707 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3708}
3709
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003710void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003711{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003712 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003713 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3714
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003715 if (isLayerTripleBufferingDisabled())
3716 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003717
3718 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003719 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003720 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003721 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003722 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3723 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003724 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003725}
3726
Dan Stozab90cf072015-03-05 11:05:59 -08003727void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3728{
3729 result.appendFormat("Static screen stats:\n");
3730 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3731 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3732 float percent = 100.0f *
3733 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3734 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3735 b + 1, bucketTimeSec, percent);
3736 }
3737 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3738 float percent = 100.0f *
3739 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3740 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3741 NUM_BUCKETS - 1, bucketTimeSec, percent);
3742}
3743
Dan Stozae77c7662016-05-13 11:37:28 -07003744void SurfaceFlinger::recordBufferingStats(const char* layerName,
3745 std::vector<OccupancyTracker::Segment>&& history) {
3746 Mutex::Autolock lock(mBufferingStatsMutex);
3747 auto& stats = mBufferingStats[layerName];
3748 for (const auto& segment : history) {
3749 if (!segment.usedThirdBuffer) {
3750 stats.twoBufferTime += segment.totalTime;
3751 }
3752 if (segment.occupancyAverage < 1.0f) {
3753 stats.doubleBufferedTime += segment.totalTime;
3754 } else if (segment.occupancyAverage < 2.0f) {
3755 stats.tripleBufferedTime += segment.totalTime;
3756 }
3757 ++stats.numSegments;
3758 stats.totalTime += segment.totalTime;
3759 }
3760}
3761
Brian Andersond6927fb2016-07-23 23:37:30 -07003762void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3763 result.appendFormat("Layer frame timestamps:\n");
3764
3765 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3766 const size_t count = currentLayers.size();
3767 for (size_t i=0 ; i<count ; i++) {
3768 currentLayers[i]->dumpFrameEvents(result);
3769 }
3770}
3771
Dan Stozae77c7662016-05-13 11:37:28 -07003772void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3773 result.append("Buffering stats:\n");
3774 result.append(" [Layer name] <Active time> <Two buffer> "
3775 "<Double buffered> <Triple buffered>\n");
3776 Mutex::Autolock lock(mBufferingStatsMutex);
3777 typedef std::tuple<std::string, float, float, float> BufferTuple;
3778 std::map<float, BufferTuple, std::greater<float>> sorted;
3779 for (const auto& statsPair : mBufferingStats) {
3780 const char* name = statsPair.first.c_str();
3781 const BufferingStats& stats = statsPair.second;
3782 if (stats.numSegments == 0) {
3783 continue;
3784 }
3785 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3786 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3787 stats.totalTime;
3788 float doubleBufferRatio = static_cast<float>(
3789 stats.doubleBufferedTime) / stats.totalTime;
3790 float tripleBufferRatio = static_cast<float>(
3791 stats.tripleBufferedTime) / stats.totalTime;
3792 sorted.insert({activeTime, {name, twoBufferRatio,
3793 doubleBufferRatio, tripleBufferRatio}});
3794 }
3795 for (const auto& sortedPair : sorted) {
3796 float activeTime = sortedPair.first;
3797 const BufferTuple& values = sortedPair.second;
3798 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3799 std::get<0>(values).c_str(), activeTime,
3800 std::get<1>(values), std::get<2>(values),
3801 std::get<3>(values));
3802 }
3803 result.append("\n");
3804}
3805
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003806void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3807 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003808 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003809
3810 // TODO: print out if wide-color mode is active or not
3811
3812 for (size_t d = 0; d < mDisplays.size(); d++) {
3813 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3814 int32_t hwcId = displayDevice->getHwcDisplayId();
3815 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3816 continue;
3817 }
3818
3819 result.appendFormat("Display %d color modes:\n", hwcId);
3820 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3821 for (auto&& mode : modes) {
3822 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3823 }
3824
3825 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3826 result.appendFormat(" Current color mode: %s (%d)\n",
3827 decodeColorMode(currentMode).c_str(), currentMode);
3828 }
3829 result.append("\n");
3830}
3831
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003832LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003833 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003834 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3835 const State& state = useDrawing ? mDrawingState : mCurrentState;
3836 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003837 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003838 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003839 });
3840
3841 return layersProto;
3842}
3843
Mathias Agopian74d211a2013-04-22 16:55:35 +02003844void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3845 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003846{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003847 bool colorize = false;
3848 if (index < args.size()
3849 && (args[index] == String16("--color"))) {
3850 colorize = true;
3851 index++;
3852 }
3853
3854 Colorizer colorizer(colorize);
3855
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003856 // figure out if we're stuck somewhere
3857 const nsecs_t now = systemTime();
3858 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3859 const nsecs_t inTransaction(mDebugInTransaction);
3860 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3861 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3862
3863 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003864 * Dump library configuration.
3865 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003866
3867 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003868 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003869 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003870 appendSfConfigString(result);
3871 appendUiConfigString(result);
3872 appendGuiConfigString(result);
3873 result.append("\n");
3874
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003875 result.append("\nWide-Color information:\n");
3876 dumpWideColorInfo(result);
3877
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003878 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003879 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003880 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003881 result.append(SyncFeatures::getInstance().toString());
3882 result.append("\n");
3883
Dan Stoza9e56aa02015-11-02 13:00:03 -08003884 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3885
Andy McFadden41d67d72014-04-25 16:58:34 -07003886 colorizer.bold(result);
3887 result.append("DispSync configuration: ");
3888 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003889 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003890 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003891 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003892 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003893 result.append("\n");
3894
Dan Stozab90cf072015-03-05 11:05:59 -08003895 // Dump static screen stats
3896 result.append("\n");
3897 dumpStaticScreenStats(result);
3898 result.append("\n");
3899
Dan Stozae77c7662016-05-13 11:37:28 -07003900 dumpBufferingStats(result);
3901
Andy McFadden4803b742012-09-24 19:07:20 -07003902 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003903 * Dump the visible layer list
3904 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003905 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003906 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003907 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003908
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003909 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003910 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3911 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003912
3913 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003914 * Dump Display state
3915 */
3916
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003917 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003918 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003919 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003920 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3921 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003922 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003923 }
3924
3925 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003926 * Dump SurfaceFlinger global state
3927 */
3928
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003929 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003930 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003931 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003932
Mathias Agopian888c8222012-08-04 21:10:38 -07003933 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003934 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003935
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003936 colorizer.bold(result);
3937 result.appendFormat("EGL implementation : %s\n",
3938 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3939 colorizer.reset(result);
3940 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003941 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003942
Mathias Agopian875d8e12013-06-07 15:35:48 -07003943 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003944
Mathias Agopian42977342012-08-05 00:40:46 -07003945 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003946 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3947 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003948 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003949 " last eglSwapBuffers() time: %f us\n"
3950 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003951 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003952 " refresh-rate : %f fps\n"
3953 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003954 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003955 " gpu_to_cpu_unsupported : %d\n"
3956 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003957 mLastSwapBufferTime/1000.0,
3958 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003959 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003960 1e9 / activeConfig->getVsyncPeriod(),
3961 activeConfig->getDpiX(),
3962 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003963 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003964
Mathias Agopian74d211a2013-04-22 16:55:35 +02003965 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003966 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003967
Mathias Agopian74d211a2013-04-22 16:55:35 +02003968 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003969 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003970
3971 /*
3972 * VSYNC state
3973 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003974 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003975 result.append("\n");
3976
3977 /*
3978 * HWC layer minidump
3979 */
3980 for (size_t d = 0; d < mDisplays.size(); d++) {
3981 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3982 int32_t hwcId = displayDevice->getHwcDisplayId();
3983 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3984 continue;
3985 }
3986
3987 result.appendFormat("Display %d HWC layers:\n", hwcId);
3988 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003989 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003990 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003991 });
Dan Stozae22aec72016-08-01 13:20:59 -07003992 result.append("\n");
3993 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003994
3995 /*
3996 * Dump HWComposer state
3997 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003998 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003999 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004000 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004001 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004002 result.appendFormat(" h/w composer %s\n",
4003 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004004 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004005
4006 /*
4007 * Dump gralloc state
4008 */
4009 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4010 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004011
4012 /*
4013 * Dump VrFlinger state if in use.
4014 */
4015 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4016 result.append("VrFlinger state:\n");
4017 result.append(mVrFlinger->Dump().c_str());
4018 result.append("\n");
4019 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004020}
4021
Mathias Agopian13127d82013-03-05 17:47:11 -08004022const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004023SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004024 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004025 wp<IBinder> dpy;
4026 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4027 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4028 dpy = mDisplays.keyAt(i);
4029 break;
4030 }
4031 }
4032 if (dpy == NULL) {
4033 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4034 // Just use the primary display so we have something to return
4035 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4036 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004037 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004038}
4039
Keun young Park63f165f2012-08-31 10:53:36 -07004040bool SurfaceFlinger::startDdmConnection()
4041{
4042 void* libddmconnection_dso =
4043 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4044 if (!libddmconnection_dso) {
4045 return false;
4046 }
4047 void (*DdmConnection_start)(const char* name);
4048 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004049 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004050 if (!DdmConnection_start) {
4051 dlclose(libddmconnection_dso);
4052 return false;
4053 }
4054 (*DdmConnection_start)(getServiceName());
4055 return true;
4056}
4057
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004058status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004059 switch (code) {
4060 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004061 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004062 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004063 case CLEAR_ANIMATION_FRAME_STATS:
4064 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004065 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004066 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004067 case ENABLE_VSYNC_INJECTIONS:
4068 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004069 {
4070 // codes that require permission check
4071 IPCThreadState* ipc = IPCThreadState::self();
4072 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004073 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004074 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004075 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004076 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004077 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004078 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004079 break;
4080 }
Robert Carr1db73f62016-12-21 12:58:51 -08004081 /*
4082 * Calling setTransactionState is safe, because you need to have been
4083 * granted a reference to Client* and Handle* to do anything with it.
4084 *
4085 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4086 */
4087 case SET_TRANSACTION_STATE:
4088 case CREATE_SCOPED_CONNECTION:
4089 {
4090 return OK;
4091 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004092 case CAPTURE_SCREEN:
4093 {
4094 // codes that require permission check
4095 IPCThreadState* ipc = IPCThreadState::self();
4096 const int pid = ipc->getCallingPid();
4097 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004098 if ((uid != AID_GRAPHICS) &&
4099 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004100 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004101 return PERMISSION_DENIED;
4102 }
4103 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004104 }
chaviwa76b2712017-09-20 12:02:26 -07004105 case CAPTURE_LAYERS: {
4106 IPCThreadState* ipc = IPCThreadState::self();
4107 const int pid = ipc->getCallingPid();
4108 const int uid = ipc->getCallingUid();
4109 if ((uid != AID_GRAPHICS) &&
4110 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4111 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4112 return PERMISSION_DENIED;
4113 }
4114 break;
4115 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004116 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004117 return OK;
4118}
4119
4120status_t SurfaceFlinger::onTransact(
4121 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4122{
4123 status_t credentialCheck = CheckTransactCodeCredentials(code);
4124 if (credentialCheck != OK) {
4125 return credentialCheck;
4126 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004127
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004128 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4129 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004130 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004131 IPCThreadState* ipc = IPCThreadState::self();
4132 const int uid = ipc->getCallingUid();
4133 if (CC_UNLIKELY(uid != AID_SYSTEM
4134 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004135 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004136 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004137 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004138 return PERMISSION_DENIED;
4139 }
4140 int n;
4141 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004142 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004143 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004144 return NO_ERROR;
4145 case 1002: // SHOW_UPDATES
4146 n = data.readInt32();
4147 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004148 invalidateHwcGeometry();
4149 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004150 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004151 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004152 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004153 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004154 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004155 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004156 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004157 setTransactionFlags(
4158 eTransactionNeeded|
4159 eDisplayTransactionNeeded|
4160 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004161 return NO_ERROR;
4162 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004163 case 1006:{ // send empty update
4164 signalRefresh();
4165 return NO_ERROR;
4166 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004167 case 1008: // toggle use of hw composer
4168 n = data.readInt32();
4169 mDebugDisableHWC = n ? 1 : 0;
4170 invalidateHwcGeometry();
4171 repaintEverything();
4172 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004173 case 1009: // toggle use of transform hint
4174 n = data.readInt32();
4175 mDebugDisableTransformHint = n ? 1 : 0;
4176 invalidateHwcGeometry();
4177 repaintEverything();
4178 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004179 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004180 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004181 reply->writeInt32(0);
4182 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004183 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004184 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004185 return NO_ERROR;
4186 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004187 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004188 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004189 return NO_ERROR;
4190 }
4191 case 1014: {
4192 // daltonize
4193 n = data.readInt32();
4194 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004195 case 1:
4196 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4197 break;
4198 case 2:
4199 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4200 break;
4201 case 3:
4202 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4203 break;
4204 default:
4205 mDaltonizer.setType(ColorBlindnessType::None);
4206 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004207 }
4208 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004209 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004210 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004211 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004212 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004213 invalidateHwcGeometry();
4214 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004215 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004216 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004217 case 1015: {
4218 // apply a color matrix
4219 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004220 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004221 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004222 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004223 for (size_t j = 0; j < 4; j++) {
4224 mColorMatrix[i][j] = data.readFloat();
4225 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004226 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004227 } else {
4228 mColorMatrix = mat4();
4229 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004230
4231 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4232 // the division by w in the fragment shader
4233 float4 lastRow(transpose(mColorMatrix)[3]);
4234 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4235 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4236 }
4237
Alan Viverette9c5a3332013-09-12 20:04:35 -07004238 invalidateHwcGeometry();
4239 repaintEverything();
4240 return NO_ERROR;
4241 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004242 // This is an experimental interface
4243 // Needs to be shifted to proper binder interface when we productize
4244 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004245 n = data.readInt32();
4246 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004247 return NO_ERROR;
4248 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004249 case 1017: {
4250 n = data.readInt32();
4251 mForceFullDamage = static_cast<bool>(n);
4252 return NO_ERROR;
4253 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004254 case 1018: { // Modify Choreographer's phase offset
4255 n = data.readInt32();
4256 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4257 return NO_ERROR;
4258 }
4259 case 1019: { // Modify SurfaceFlinger's phase offset
4260 n = data.readInt32();
4261 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4262 return NO_ERROR;
4263 }
Irvel468051e2016-06-13 16:44:44 -07004264 case 1020: { // Layer updates interceptor
4265 n = data.readInt32();
4266 if (n) {
4267 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004268 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004269 }
4270 else{
4271 ALOGV("Interceptor disabled");
4272 mInterceptor.disable();
4273 }
4274 return NO_ERROR;
4275 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004276 case 1021: { // Disable HWC virtual displays
4277 n = data.readInt32();
4278 mUseHwcVirtualDisplays = !n;
4279 return NO_ERROR;
4280 }
Romain Guy0147a172017-06-01 13:53:56 -07004281 case 1022: { // Set saturation boost
4282 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4283
4284 invalidateHwcGeometry();
4285 repaintEverything();
4286 return NO_ERROR;
4287 }
Romain Guy54f154a2017-10-24 21:40:32 +01004288 case 1023: { // Set native mode
4289 mForceNativeColorMode = data.readInt32() == 1;
4290
4291 invalidateHwcGeometry();
4292 repaintEverything();
4293 return NO_ERROR;
4294 }
4295 case 1024: { // Is wide color gamut rendering/color management supported?
4296 reply->writeBool(hasWideColorDisplay);
4297 return NO_ERROR;
4298 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004299 case 1025: { // tracing
4300 n = data.readInt32();
4301 if (n) {
4302 ALOGV("LayerTracing enabled");
4303 mTracing.enable();
4304 doTracing("tracing.enable");
4305 reply->writeInt32(NO_ERROR);
4306 } else {
4307 ALOGV("LayerTracing disabled");
4308 status_t err = mTracing.disable();
4309 reply->writeInt32(err);
4310 }
4311 return NO_ERROR;
4312 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004313 }
4314 }
4315 return err;
4316}
4317
Steven Thomas6d8110b2017-08-31 18:24:21 -07004318void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004319 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004320 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004321}
4322
Steven Thomas6d8110b2017-08-31 18:24:21 -07004323void SurfaceFlinger::repaintEverything() {
4324 ConditionalLock _l(mStateLock,
4325 std::this_thread::get_id() != mMainThreadId);
4326 repaintEverythingLocked();
4327}
4328
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004329// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4330class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004331public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004332 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4333 ~WindowDisconnector() {
4334 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004335 }
4336
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004337private:
4338 ANativeWindow* mWindow;
4339 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004340};
4341
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004342status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4343 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4344 int32_t minLayerZ, int32_t maxLayerZ,
4345 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004346 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004347 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004348
chaviwa76b2712017-09-20 12:02:26 -07004349 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4350
4351 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4352 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4353
4354 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4355 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004356 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004357}
4358
4359status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004360 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
4361 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004362 ATRACE_CALL();
4363
4364 class LayerRenderArea : public RenderArea {
4365 public:
chaviw7206d492017-11-10 16:16:12 -08004366 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004367 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004368 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004369 const Transform& getTransform() const override {
4370 // Make the top level transform the inverse the transform and it's parent so it sets
4371 // the whole capture back to 0,0
4372 return *new Transform(mLayer->getTransform().inverse());
4373 }
4374 Rect getBounds() const override {
4375 const Layer::State& layerState(mLayer->getDrawingState());
4376 return Rect(layerState.active.w, layerState.active.h);
4377 }
4378 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4379 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4380 bool isSecure() const override { return false; }
4381 bool needsFiltering() const override { return false; }
4382
chaviw7206d492017-11-10 16:16:12 -08004383 Rect getSourceCrop() const override {
4384 if (mCrop.isEmpty()) {
4385 return getBounds();
4386 } else {
4387 return mCrop;
4388 }
4389 }
chaviwa76b2712017-09-20 12:02:26 -07004390 bool getWideColorSupport() const override { return false; }
4391 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4392
4393 private:
chaviw7206d492017-11-10 16:16:12 -08004394 const sp<Layer> mLayer;
4395 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004396 };
4397
4398 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4399 auto parent = layerHandle->owner.promote();
4400
chaviw7206d492017-11-10 16:16:12 -08004401 if (parent == nullptr || parent->isPendingRemoval()) {
4402 ALOGE("captureLayers called with a removed parent");
4403 return NAME_NOT_FOUND;
4404 }
4405
4406 Rect crop(sourceCrop);
4407 if (sourceCrop.width() <= 0) {
4408 crop.left = 0;
4409 crop.right = parent->getCurrentState().active.w;
4410 }
4411
4412 if (sourceCrop.height() <= 0) {
4413 crop.top = 0;
4414 crop.bottom = parent->getCurrentState().active.h;
4415 }
4416
4417 int32_t reqWidth = crop.width() * frameScale;
4418 int32_t reqHeight = crop.height() * frameScale;
4419
4420 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4421
chaviwa76b2712017-09-20 12:02:26 -07004422 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4423 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4424 if (!layer->isVisible()) {
4425 return;
4426 }
4427 visitor(layer);
4428 });
4429 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004430 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004431}
4432
4433status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4434 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004435 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004436 bool useIdentityTransform) {
4437 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004438
chaviwa76b2712017-09-20 12:02:26 -07004439 renderArea.updateDimensions();
4440
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004441 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4442 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4443 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4444 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004445
4446 // This mutex protects syncFd and captureResult for communication of the return values from the
4447 // main thread back to this Binder thread
4448 std::mutex captureMutex;
4449 std::condition_variable captureCondition;
4450 std::unique_lock<std::mutex> captureLock(captureMutex);
4451 int syncFd = -1;
4452 std::optional<status_t> captureResult;
4453
4454 sp<LambdaMessage> message = new LambdaMessage([&]() {
4455 // If there is a refresh pending, bug out early and tell the binder thread to try again
4456 // after the refresh.
4457 if (mRefreshPending) {
4458 ATRACE_NAME("Skipping screenshot for now");
4459 std::unique_lock<std::mutex> captureLock(captureMutex);
4460 captureResult = std::make_optional<status_t>(EAGAIN);
4461 captureCondition.notify_one();
4462 return;
4463 }
4464
4465 status_t result = NO_ERROR;
4466 int fd = -1;
4467 {
4468 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004469 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4470 useIdentityTransform, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004471 }
4472
4473 {
4474 std::unique_lock<std::mutex> captureLock(captureMutex);
4475 syncFd = fd;
4476 captureResult = std::make_optional<status_t>(result);
4477 captureCondition.notify_one();
4478 }
4479 });
4480
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004481 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004482 if (result == NO_ERROR) {
4483 captureCondition.wait(captureLock, [&]() { return captureResult; });
4484 while (*captureResult == EAGAIN) {
4485 captureResult.reset();
4486 result = postMessageAsync(message);
4487 if (result != NO_ERROR) {
4488 return result;
4489 }
4490 captureCondition.wait(captureLock, [&]() { return captureResult; });
4491 }
4492 result = *captureResult;
4493 }
4494
4495 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004496 sync_wait(syncFd, -1);
4497 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004498 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004499
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004500 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004501}
4502
chaviwa76b2712017-09-20 12:02:26 -07004503void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4504 TraverseLayersFunction traverseLayers, bool yswap,
4505 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004506 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004507
Mathias Agopian3f844832013-08-07 21:24:32 -07004508 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004509
4510 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004511 const auto raWidth = renderArea.getWidth();
4512 const auto raHeight = renderArea.getHeight();
4513
4514 const auto reqWidth = renderArea.getReqWidth();
4515 const auto reqHeight = renderArea.getReqHeight();
4516 Rect sourceCrop = renderArea.getSourceCrop();
4517
4518 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4519 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004520
Dan Stozac1879002014-05-22 15:59:05 -07004521 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004522 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004523 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004524 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004525 }
4526
4527 // ensure that sourceCrop is inside screen
4528 if (sourceCrop.left < 0) {
4529 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4530 }
chaviwa76b2712017-09-20 12:02:26 -07004531 if (sourceCrop.right > raWidth) {
4532 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004533 }
4534 if (sourceCrop.top < 0) {
4535 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4536 }
chaviwa76b2712017-09-20 12:02:26 -07004537 if (sourceCrop.bottom > raHeight) {
4538 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004539 }
4540
chaviwa76b2712017-09-20 12:02:26 -07004541 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004542 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4543 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004544
Mathias Agopian180f10d2013-04-10 22:55:41 -07004545 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004546 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004547
4548 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004549 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4550 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004551 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004552
4553 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004554 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004555
chaviwa76b2712017-09-20 12:02:26 -07004556 traverseLayers([&](Layer* layer) {
4557 if (filtering) layer->setFiltering(true);
4558 layer->draw(renderArea, useIdentityTransform);
4559 if (filtering) layer->setFiltering(false);
4560 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004561}
4562
Dan Stozaabcda352017-06-01 14:37:39 -07004563// A simple RAII class that holds an EGLImage and destroys it either:
4564// a) When the destroy() method is called
4565// b) When the object goes out of scope
4566class ImageHolder {
4567public:
4568 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4569 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004570
Dan Stozaabcda352017-06-01 14:37:39 -07004571 void destroy() {
4572 if (mImage != EGL_NO_IMAGE_KHR) {
4573 eglDestroyImageKHR(mDisplay, mImage);
4574 mImage = EGL_NO_IMAGE_KHR;
4575 }
4576 }
4577
4578private:
4579 const EGLDisplay mDisplay;
4580 EGLImageKHR mImage;
4581};
4582
chaviwa76b2712017-09-20 12:02:26 -07004583status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4584 TraverseLayersFunction traverseLayers,
4585 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004586 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004587 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004588 ATRACE_CALL();
4589
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004590 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004591
4592 traverseLayers([&](Layer* layer) {
4593 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4594 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004595
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004596 if (secureLayerIsVisible) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004597 ALOGW("FB is protected: PERMISSION_DENIED");
4598 return PERMISSION_DENIED;
4599 }
4600
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004601 int syncFd = -1;
4602 // create an EGLImage from the buffer so we can later
4603 // turn it into a texture
4604 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4605 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4606 if (image == EGL_NO_IMAGE_KHR) {
4607 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004608 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004609
Dan Stozaabcda352017-06-01 14:37:39 -07004610 // This will automatically destroy the image if we return before calling its destroy method
4611 ImageHolder imageHolder(mEGLDisplay, image);
4612
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004613 // this binds the given EGLImage as a framebuffer for the
4614 // duration of this scope.
4615 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004616 if (imageBond.getStatus() != NO_ERROR) {
4617 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004618 return INVALID_OPERATION;
4619 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004620
Dan Stozaabcda352017-06-01 14:37:39 -07004621 // this will in fact render into our dequeued buffer
4622 // via an FBO, which means we didn't have to create
4623 // an EGLSurface and therefore we're not
4624 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004625 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004626
Dan Stozaabcda352017-06-01 14:37:39 -07004627 // Attempt to create a sync khr object that can produce a sync point. If that
4628 // isn't available, create a non-dupable sync object in the fallback path and
4629 // wait on it directly.
4630 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4631 if (!DEBUG_SCREENSHOTS) {
4632 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4633 // native fence fd will not be populated until flush() is done.
4634 getRenderEngine().flush();
4635 }
4636
4637 if (sync != EGL_NO_SYNC_KHR) {
4638 // get the sync fd
4639 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4640 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4641 ALOGW("captureScreen: failed to dup sync khr object");
4642 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004643 }
Dan Stozaabcda352017-06-01 14:37:39 -07004644 eglDestroySyncKHR(mEGLDisplay, sync);
4645 } else {
4646 // fallback path
4647 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004648 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004649 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4650 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4651 EGLint eglErr = eglGetError();
4652 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4653 ALOGW("captureScreen: fence wait timed out");
4654 } else {
4655 ALOGW_IF(eglErr != EGL_SUCCESS,
4656 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004657 }
4658 eglDestroySyncKHR(mEGLDisplay, sync);
4659 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004660 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004661 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004662 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004663 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004664
4665 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004666 const auto reqWidth = renderArea.getReqWidth();
4667 const auto reqHeight = renderArea.getReqHeight();
4668
Dan Stozaabcda352017-06-01 14:37:39 -07004669 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4670 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004671 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004672 delete [] pixels;
4673 }
4674
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004675 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004676 imageHolder.destroy();
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004677 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004678}
4679
Mathias Agopiand5556842013-09-19 17:08:37 -07004680void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004681 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004682 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004683 for (size_t y = 0; y < h; y++) {
4684 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4685 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004686 if (p[x] != 0xFF000000) return;
4687 }
4688 }
chaviwa76b2712017-09-20 12:02:26 -07004689 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004690
Robert Carr2047fae2016-11-28 14:09:09 -08004691 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004692 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004693 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004694 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4695 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4696 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4697 static_cast<float>(state.color.a));
4698 i++;
4699 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004700 }
4701}
4702
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004703// ---------------------------------------------------------------------------
4704
Dan Stoza412903f2017-04-27 13:42:17 -07004705void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4706 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004707}
4708
Dan Stoza412903f2017-04-27 13:42:17 -07004709void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4710 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004711}
4712
chaviwa76b2712017-09-20 12:02:26 -07004713void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4714 int32_t maxLayerZ,
4715 const LayerVector::Visitor& visitor) {
4716 // We loop through the first level of layers without traversing,
4717 // as we need to interpret min/max layer Z in the top level Z space.
4718 for (const auto& layer : mDrawingState.layersSortedByZ) {
4719 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4720 continue;
4721 }
4722 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004723 // relative layers are traversed in Layer::traverseInZOrder
4724 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004725 continue;
4726 }
4727 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4728 if (!layer->isVisible()) {
4729 return;
4730 }
4731 visitor(layer);
4732 });
4733 }
4734}
4735
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004736}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004737
4738
4739#if defined(__gl_h_)
4740#error "don't include gl/gl.h in this file"
4741#endif
4742
4743#if defined(__gl2_h_)
4744#error "don't include gl2/gl2.h in this file"
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004745#endif