blob: ea4f495d59d3ef5eb8739b15c273e0f8bb6756c1 [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(),
652 vrFlingerRequestDisplayCallback);
653 if (!mVrFlinger) {
654 ALOGE("Failed to start vrflinger");
655 }
656 }
657
Jamie Gennisd1700752013-10-14 12:22:52 -0700658 mEventControlThread = new EventControlThread(this);
659 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
660
Mathias Agopian92a979a2012-08-02 18:32:23 -0700661 // initialize our drawing state
662 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700663
Andy McFadden13a082e2012-08-24 10:16:42 -0700664 // set initial conditions (e.g. unblank default device)
665 initializeDisplays();
666
Dan Stoza4e637772016-07-28 13:31:51 -0700667 mRenderEngine->primeCache();
668
Wei Wangf9b05ee2017-07-19 20:59:39 -0700669 // Inform native graphics APIs whether the present timestamp is supported:
670 if (getHwComposer().hasCapability(
671 HWC2::Capability::PresentFenceIsNotReliable)) {
672 mStartPropertySetThread = new StartPropertySetThread(false);
673 } else {
674 mStartPropertySetThread = new StartPropertySetThread(true);
675 }
676
677 if (mStartPropertySetThread->Start() != NO_ERROR) {
678 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800679 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800680
Dan Stoza9e56aa02015-11-02 13:00:03 -0800681 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700682}
683
Romain Guy11d63f42017-07-20 12:47:14 -0700684void SurfaceFlinger::readPersistentProperties() {
685 char value[PROPERTY_VALUE_MAX];
686
687 property_get("persist.sys.sf.color_saturation", value, "1.0");
688 mSaturation = atof(value);
689 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100690
691 property_get("persist.sys.sf.native_mode", value, "0");
692 mForceNativeColorMode = atoi(value) == 1;
693 if (mForceNativeColorMode) {
694 ALOGV("Forcing native color mode");
695 }
Romain Guy11d63f42017-07-20 12:47:14 -0700696}
697
Mathias Agopiana67e4182012-06-19 17:26:12 -0700698void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800699 // Start boot animation service by setting a property mailbox
700 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700701 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800702 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700703 if (mStartPropertySetThread->join() != NO_ERROR) {
704 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800705 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700706}
707
Mathias Agopian875d8e12013-06-07 15:35:48 -0700708size_t SurfaceFlinger::getMaxTextureSize() const {
709 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700710}
711
Mathias Agopian875d8e12013-06-07 15:35:48 -0700712size_t SurfaceFlinger::getMaxViewportDims() const {
713 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700714}
715
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800716// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800717
Jamie Gennis582270d2011-08-17 18:19:00 -0700718bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800719 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800720 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800721 return authenticateSurfaceTextureLocked(bufferProducer);
722}
723
724bool SurfaceFlinger::authenticateSurfaceTextureLocked(
725 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800726 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700727 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800728}
729
Brian Anderson6b376712017-04-04 10:51:39 -0700730status_t SurfaceFlinger::getSupportedFrameTimestamps(
731 std::vector<FrameEvent>* outSupported) const {
732 *outSupported = {
733 FrameEvent::REQUESTED_PRESENT,
734 FrameEvent::ACQUIRE,
735 FrameEvent::LATCH,
736 FrameEvent::FIRST_REFRESH_START,
737 FrameEvent::LAST_REFRESH_START,
738 FrameEvent::GPU_COMPOSITION_DONE,
739 FrameEvent::DEQUEUE_READY,
740 FrameEvent::RELEASE,
741 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700742 ConditionalLock _l(mStateLock,
743 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700744 if (!getHwComposer().hasCapability(
745 HWC2::Capability::PresentFenceIsNotReliable)) {
746 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
747 }
748 return NO_ERROR;
749}
750
Dan Stoza7f7da322014-05-02 15:26:25 -0700751status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
752 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700753 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700754 return BAD_VALUE;
755 }
756
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500757 if (!display.get())
758 return NAME_NOT_FOUND;
759
Jesse Hall692c7232012-11-08 15:41:56 -0800760 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700761 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800762 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700763 type = i;
764 break;
765 }
766 }
767
768 if (type < 0) {
769 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700770 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700771
Mathias Agopian8b736f12012-08-13 17:54:26 -0700772 // TODO: Not sure if display density should handled by SF any longer
773 class Density {
774 static int getDensityFromProperty(char const* propName) {
775 char property[PROPERTY_VALUE_MAX];
776 int density = 0;
777 if (property_get(propName, property, NULL) > 0) {
778 density = atoi(property);
779 }
780 return density;
781 }
782 public:
783 static int getEmuDensity() {
784 return getDensityFromProperty("qemu.sf.lcd_density"); }
785 static int getBuildDensity() {
786 return getDensityFromProperty("ro.sf.lcd_density"); }
787 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700788
Dan Stoza7f7da322014-05-02 15:26:25 -0700789 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700790
Steven Thomas6d8110b2017-08-31 18:24:21 -0700791 ConditionalLock _l(mStateLock,
792 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800793 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700794 DisplayInfo info = DisplayInfo();
795
Dan Stoza9e56aa02015-11-02 13:00:03 -0800796 float xdpi = hwConfig->getDpiX();
797 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700798
799 if (type == DisplayDevice::DISPLAY_PRIMARY) {
800 // The density of the device is provided by a build property
801 float density = Density::getBuildDensity() / 160.0f;
802 if (density == 0) {
803 // the build doesn't provide a density -- this is wrong!
804 // use xdpi instead
805 ALOGE("ro.sf.lcd_density must be defined as a build property");
806 density = xdpi / 160.0f;
807 }
808 if (Density::getEmuDensity()) {
809 // if "qemu.sf.lcd_density" is specified, it overrides everything
810 xdpi = ydpi = density = Density::getEmuDensity();
811 density /= 160.0f;
812 }
813 info.density = density;
814
815 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700816 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000817 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 } else {
819 // TODO: where should this value come from?
820 static const int TV_DENSITY = 213;
821 info.density = TV_DENSITY / 160.0f;
822 info.orientation = 0;
823 }
824
Dan Stoza9e56aa02015-11-02 13:00:03 -0800825 info.w = hwConfig->getWidth();
826 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 info.xdpi = xdpi;
828 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900830 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831
Andy McFadden91b2ca82014-06-13 14:04:23 -0700832 // This is how far in advance a buffer must be queued for
833 // presentation at a given time. If you want a buffer to appear
834 // on the screen at time N, you must submit the buffer before
835 // (N - presentationDeadline).
836 //
837 // Normally it's one full refresh period (to give SF a chance to
838 // latch the buffer), but this can be reduced by configuring a
839 // DispSync offset. Any additional delays introduced by the hardware
840 // composer or panel must be accounted for here.
841 //
842 // We add an additional 1ms to allow for processing time and
843 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800844 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800845 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700846
847 // All non-virtual displays are currently considered secure.
848 info.secure = true;
849
Michael Wright28f24d02016-07-12 13:30:53 -0700850 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700851 }
852
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 return NO_ERROR;
854}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700855
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800856status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700857 DisplayStatInfo* stats) {
858 if (stats == NULL) {
859 return BAD_VALUE;
860 }
861
862 // FIXME for now we always return stats for the primary display
863 memset(stats, 0, sizeof(*stats));
864 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
865 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
866 return NO_ERROR;
867}
868
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700869int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800870 if (display == NULL) {
871 ALOGE("%s : display is NULL", __func__);
872 return BAD_VALUE;
873 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700874
875 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700876 if (device != NULL) {
877 return device->getActiveConfig();
878 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700879
Dan Stoza24a42e92015-03-09 10:04:11 -0700880 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700881}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700882
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700883void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
884 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
885 this);
886 int32_t type = hw->getDisplayType();
887 int currentMode = hw->getActiveConfig();
888
889 if (mode == currentMode) {
890 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
891 return;
892 }
893
894 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
895 ALOGW("Trying to set config for virtual display");
896 return;
897 }
898
899 hw->setActiveConfig(mode);
900 getHwComposer().setActiveConfig(type, mode);
901}
902
903status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
904 class MessageSetActiveConfig: public MessageBase {
905 SurfaceFlinger& mFlinger;
906 sp<IBinder> mDisplay;
907 int mMode;
908 public:
909 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
910 int mode) :
911 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
912 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700913 Vector<DisplayInfo> configs;
914 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700915 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700916 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700917 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700918 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700919 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700920 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
921 if (hw == NULL) {
922 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700923 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700924 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
925 ALOGW("Attempt to set active config = %d for virtual display",
926 mMode);
927 } else {
928 mFlinger.setActiveConfigInternal(hw, mMode);
929 }
930 return true;
931 }
932 };
933 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
934 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700935 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700936}
Michael Wright28f24d02016-07-12 13:30:53 -0700937status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
938 Vector<android_color_mode_t>* outColorModes) {
939 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
940 return BAD_VALUE;
941 }
942
943 if (!display.get()) {
944 return NAME_NOT_FOUND;
945 }
946
947 int32_t type = NAME_NOT_FOUND;
948 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
949 if (display == mBuiltinDisplays[i]) {
950 type = i;
951 break;
952 }
953 }
954
955 if (type < 0) {
956 return type;
957 }
958
Steven Thomas6d8110b2017-08-31 18:24:21 -0700959 std::vector<android_color_mode_t> modes;
960 {
961 ConditionalLock _l(mStateLock,
962 std::this_thread::get_id() != mMainThreadId);
963 modes = getHwComposer().getColorModes(type);
964 }
Michael Wright28f24d02016-07-12 13:30:53 -0700965 outColorModes->clear();
966 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
967
968 return NO_ERROR;
969}
970
971android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700972 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700973 if (device != nullptr) {
974 return device->getActiveColorMode();
975 }
976 return static_cast<android_color_mode_t>(BAD_VALUE);
977}
978
979void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
980 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700981 int32_t type = hw->getDisplayType();
982 android_color_mode_t currentMode = hw->getActiveColorMode();
983
984 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700985 return;
986 }
987
988 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
989 ALOGW("Trying to set config for virtual display");
990 return;
991 }
992
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600993 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
994 hw->getDisplayType());
995
Michael Wright28f24d02016-07-12 13:30:53 -0700996 hw->setActiveColorMode(mode);
997 getHwComposer().setActiveColorMode(type, mode);
998}
999
1000
1001status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
1002 android_color_mode_t colorMode) {
1003 class MessageSetActiveColorMode: public MessageBase {
1004 SurfaceFlinger& mFlinger;
1005 sp<IBinder> mDisplay;
1006 android_color_mode_t mMode;
1007 public:
1008 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1009 android_color_mode_t mode) :
1010 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1011 virtual bool handler() {
1012 Vector<android_color_mode_t> modes;
1013 mFlinger.getDisplayColorModes(mDisplay, &modes);
1014 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1015 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001016 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1017 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001018 return true;
1019 }
1020 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1021 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001022 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1023 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001024 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001025 ALOGW("Attempt to set active color mode %s %d for virtual display",
1026 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001027 } else {
1028 mFlinger.setActiveColorModeInternal(hw, mMode);
1029 }
1030 return true;
1031 }
1032 };
1033 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1034 postMessageSync(msg);
1035 return NO_ERROR;
1036}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001037
Svetoslavd85084b2014-03-20 10:28:31 -07001038status_t SurfaceFlinger::clearAnimationFrameStats() {
1039 Mutex::Autolock _l(mStateLock);
1040 mAnimFrameTracker.clearStats();
1041 return NO_ERROR;
1042}
1043
1044status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1045 Mutex::Autolock _l(mStateLock);
1046 mAnimFrameTracker.getStats(outStats);
1047 return NO_ERROR;
1048}
1049
Dan Stozac4f471e2016-03-24 09:31:08 -07001050status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1051 HdrCapabilities* outCapabilities) const {
1052 Mutex::Autolock _l(mStateLock);
1053
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001054 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001055 if (displayDevice == nullptr) {
1056 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1057 return BAD_VALUE;
1058 }
1059
1060 std::unique_ptr<HdrCapabilities> capabilities =
1061 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1062 if (capabilities) {
1063 std::swap(*outCapabilities, *capabilities);
1064 } else {
1065 return BAD_VALUE;
1066 }
1067
1068 return NO_ERROR;
1069}
1070
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001071status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001072 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1073 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001074
Chia-I Wu90f669f2017-10-05 14:24:41 -07001075 if (mInjectVSyncs == enable) {
1076 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001077 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001078
1079 if (enable) {
1080 ALOGV("VSync Injections enabled");
1081 if (mVSyncInjector.get() == nullptr) {
1082 mVSyncInjector = new InjectVSyncSource();
1083 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1084 }
1085 mEventQueue.setEventThread(mInjectorEventThread);
1086 } else {
1087 ALOGV("VSync Injections disabled");
1088 mEventQueue.setEventThread(mSFEventThread);
1089 }
1090
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001091 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001092 });
1093 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001094 return NO_ERROR;
1095}
1096
1097status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001098 Mutex::Autolock _l(mStateLock);
1099
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001100 if (!mInjectVSyncs) {
1101 ALOGE("VSync Injections not enabled");
1102 return BAD_VALUE;
1103 }
1104 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1105 ALOGV("Injecting VSync inside SurfaceFlinger");
1106 mVSyncInjector->onInjectSyncEvent(when);
1107 }
1108 return NO_ERROR;
1109}
1110
Kalle Raitaa099a242017-01-11 11:17:29 -08001111status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1112 IPCThreadState* ipc = IPCThreadState::self();
1113 const int pid = ipc->getCallingPid();
1114 const int uid = ipc->getCallingUid();
1115 if ((uid != AID_SHELL) &&
1116 !PermissionCache::checkPermission(sDump, pid, uid)) {
1117 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1118 return PERMISSION_DENIED;
1119 }
1120
1121 // Try to acquire a lock for 1s, fail gracefully
1122 const status_t err = mStateLock.timedLock(s2ns(1));
1123 const bool locked = (err == NO_ERROR);
1124 if (!locked) {
1125 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1126 return TIMED_OUT;
1127 }
1128
1129 outLayers->clear();
1130 mCurrentState.traverseInZOrder([&](Layer* layer) {
1131 outLayers->push_back(layer->getLayerDebugInfo());
1132 });
1133
1134 mStateLock.unlock();
1135 return NO_ERROR;
1136}
1137
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001138// ----------------------------------------------------------------------------
1139
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001140sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1141 ISurfaceComposer::VsyncSource vsyncSource) {
1142 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1143 return mSFEventThread->createEventConnection();
1144 } else {
1145 return mEventThread->createEventConnection();
1146 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001147}
1148
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001149// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001150
1151void SurfaceFlinger::waitForEvent() {
1152 mEventQueue.waitMessage();
1153}
1154
1155void SurfaceFlinger::signalTransaction() {
1156 mEventQueue.invalidate();
1157}
1158
1159void SurfaceFlinger::signalLayerUpdate() {
1160 mEventQueue.invalidate();
1161}
1162
1163void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001164 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001165 mEventQueue.refresh();
1166}
1167
1168status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001169 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001170 return mEventQueue.postMessage(msg, reltime);
1171}
1172
1173status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001174 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001175 status_t res = mEventQueue.postMessage(msg, reltime);
1176 if (res == NO_ERROR) {
1177 msg->wait();
1178 }
1179 return res;
1180}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001181
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001182void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001183 do {
1184 waitForEvent();
1185 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001186}
1187
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001188void SurfaceFlinger::enableHardwareVsync() {
1189 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001190 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001191 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001192 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1193 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001195 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001196}
1197
Jesse Hall948fe0c2013-10-14 12:56:09 -07001198void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001199 Mutex::Autolock _l(mHWVsyncLock);
1200
Jesse Hall948fe0c2013-10-14 12:56:09 -07001201 if (makeAvailable) {
1202 mHWVsyncAvailable = true;
1203 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001204 // Hardware vsync is not currently available, so abort the resync
1205 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001206 return;
1207 }
1208
Dan Stoza9e56aa02015-11-02 13:00:03 -08001209 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1210 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001211
1212 mPrimaryDispSync.reset();
1213 mPrimaryDispSync.setPeriod(period);
1214
1215 if (!mPrimaryHWVsyncEnabled) {
1216 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001217 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1218 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001219 mPrimaryHWVsyncEnabled = true;
1220 }
1221}
1222
Jesse Hall948fe0c2013-10-14 12:56:09 -07001223void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001224 Mutex::Autolock _l(mHWVsyncLock);
1225 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001226 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1227 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228 mPrimaryDispSync.endResync();
1229 mPrimaryHWVsyncEnabled = false;
1230 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001231 if (makeUnavailable) {
1232 mHWVsyncAvailable = false;
1233 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001234}
1235
Tim Murray4a4e4a22016-04-19 16:29:23 +00001236void SurfaceFlinger::resyncWithRateLimit() {
1237 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001238
1239 // No explicit locking is needed here since EventThread holds a lock while calling this method
1240 static nsecs_t sLastResyncAttempted = 0;
1241 const nsecs_t now = systemTime();
1242 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001243 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001244 }
Dan Stoza57164302017-05-08 14:03:54 -07001245 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001246}
1247
Steven Thomasb02664d2017-07-26 18:48:28 -07001248void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1249 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001250 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001251 // Ignore any vsyncs from a previous hardware composer.
1252 if (sequenceId != mComposerSequenceId) {
1253 return;
1254 }
1255
1256 int32_t type;
1257 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001258 return;
1259 }
1260
Jamie Gennisd1700752013-10-14 12:22:52 -07001261 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262
Jamie Gennisd1700752013-10-14 12:22:52 -07001263 { // Scope for the lock
1264 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001265 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001266 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001268 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001269
1270 if (needsHwVsync) {
1271 enableHardwareVsync();
1272 } else {
1273 disableHardwareVsync(false);
1274 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001275}
1276
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001277void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001278 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001279 *compositorTiming = mCompositorTiming;
1280}
1281
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001282void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001283 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001284 wp<IBinder> token = mBuiltinDisplays[type];
1285
1286 // All non-virtual displays are currently considered secure.
1287 const bool isSecure = true;
1288
1289 sp<IGraphicBufferProducer> producer;
1290 sp<IGraphicBufferConsumer> consumer;
1291 BufferQueue::createBufferQueue(&producer, &consumer);
1292
1293 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1294
1295 bool hasWideColorModes = false;
1296 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1297 for (android_color_mode_t colorMode : modes) {
1298 switch (colorMode) {
1299 case HAL_COLOR_MODE_DISPLAY_P3:
1300 case HAL_COLOR_MODE_ADOBE_RGB:
1301 case HAL_COLOR_MODE_DCI_P3:
1302 hasWideColorModes = true;
1303 break;
1304 default:
1305 break;
1306 }
1307 }
Romain Guy54f154a2017-10-24 21:40:32 +01001308 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001309 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1310 token, fbs, producer, mRenderEngine->getEGLConfig(),
Romain Guy54f154a2017-10-24 21:40:32 +01001311 useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001312 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001313 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001314 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001315 defaultColorMode = HAL_COLOR_MODE_SRGB;
1316 }
1317 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001318 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001319
1320 // Add the primary display token to mDrawingState so we don't try to
1321 // recreate the DisplayDevice for the primary display.
1322 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1323
1324 // make the GLContext current so that we can create textures when creating
1325 // Layers (which may happens before we render something)
1326 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001327}
1328
Steven Thomasb02664d2017-07-26 18:48:28 -07001329void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1330 hwc2_display_t display, HWC2::Connection connection,
1331 bool primaryDisplay) {
1332 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1333 sequenceId, display,
1334 connection == HWC2::Connection::Connected ?
1335 "connected" : "disconnected",
1336 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001337
Steven Thomasb02664d2017-07-26 18:48:28 -07001338 // Only lock if we're not on the main thread. This function is normally
1339 // called on a hwbinder thread, but for the primary display it's called on
1340 // the main thread with the state lock already held, so don't attempt to
1341 // acquire it here.
1342 ConditionalLock lock(mStateLock,
1343 std::this_thread::get_id() != mMainThreadId);
1344
1345 if (primaryDisplay) {
1346 mHwc->onHotplug(display, connection);
1347 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1348 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001349 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001350 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001351 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001352 if (sequenceId != mComposerSequenceId) {
1353 return;
1354 }
1355 if (mHwc->isUsingVrComposer()) {
1356 ALOGE("External displays are not supported by the vr hardware composer.");
1357 return;
1358 }
1359 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001360 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001362 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001363 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001364 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1365 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001366 }
1367 setTransactionFlags(eDisplayTransactionNeeded);
1368
Andy McFadden9e9689c2012-10-10 18:17:51 -07001369 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001370 }
Mathias Agopian86303202012-07-24 22:46:10 -07001371}
1372
Steven Thomasb02664d2017-07-26 18:48:28 -07001373void SurfaceFlinger::onRefreshReceived(int sequenceId,
1374 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001375 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 if (sequenceId != mComposerSequenceId) {
1377 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001378 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001379 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001380}
1381
Dan Stoza9e56aa02015-11-02 13:00:03 -08001382void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001383 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001385 getHwComposer().setVsyncEnabled(disp,
1386 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001387}
1388
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001389// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001390void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001391 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001392 // Clear the drawing state so that the logic inside of
1393 // handleTransactionLocked will fire. It will determine the delta between
1394 // mCurrentState and mDrawingState and re-apply all changes when we make the
1395 // transition.
1396 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001397 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001398 mDisplays.clear();
1399}
1400
Steven Thomas050b2c82017-03-06 11:45:16 -08001401void SurfaceFlinger::updateVrFlinger() {
1402 if (!mVrFlinger)
1403 return;
1404 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1405 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001406 return;
1407 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408
Steven Thomasb02664d2017-07-26 18:48:28 -07001409 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1410 ALOGE("Vr flinger is only supported for remote hardware composer"
1411 " service connections. Ignoring request to transition to vr"
1412 " flinger.");
1413 mVrFlingerRequestsDisplay = false;
1414 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001415 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001417 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001418
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 int currentDisplayPowerMode = getDisplayDeviceLocked(
1420 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001421
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001423 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001424 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001425
Steven Thomasb02664d2017-07-26 18:48:28 -07001426 resetDisplayState();
1427 mHwc.reset(); // Delete the current instance before creating the new one
1428 mHwc.reset(new HWComposer(
1429 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1430 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001431
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1433 "Switched to non-remote hardware composer");
1434
1435 if (vrFlingerRequestsDisplay) {
1436 mVrFlinger->GrantDisplayOwnership();
1437 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001438 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001439 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001440
1441 mVisibleRegionsDirty = true;
1442 invalidateHwcGeometry();
1443
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001444 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001445 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1446 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1447 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001448
Steven Thomasb02664d2017-07-26 18:48:28 -07001449 // Reset the timing values to account for the period of the swapped in HWC
1450 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1451 const nsecs_t period = activeConfig->getVsyncPeriod();
1452 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001453
Steven Thomasb02664d2017-07-26 18:48:28 -07001454 // Use phase of 0 since phase is not known.
1455 // Use latency of 0, which will snap to the ideal latency.
1456 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001457
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001458 android_atomic_or(1, &mRepaintEverything);
1459 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001460}
1461
Mathias Agopian4fec8732012-06-29 14:12:52 -07001462void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001463 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001464 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001465 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001466 bool frameMissed = !mHadClientComposition &&
1467 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001468 (mPreviousPresentFence->getSignalTime() ==
1469 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001470 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001471 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001472 signalLayerUpdate();
1473 break;
1474 }
1475
Steven Thomas050b2c82017-03-06 11:45:16 -08001476 // Now that we're going to make it to the handleMessageTransaction()
1477 // call below it's safe to call updateVrFlinger(), which will
1478 // potentially trigger a display handoff.
1479 updateVrFlinger();
1480
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481 bool refreshNeeded = handleMessageTransaction();
1482 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001483 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001484 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001485 // Signal a refresh if a transaction modified the window state,
1486 // a new buffer was latched, or if HWC has requested a full
1487 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001488 signalRefresh();
1489 }
1490 break;
1491 }
1492 case MessageQueue::REFRESH: {
1493 handleMessageRefresh();
1494 break;
1495 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001496 }
1497}
1498
Dan Stoza6b9454d2014-11-07 16:00:59 -08001499bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001500 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001501 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001502 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001503 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001504 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001505 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001506}
1507
Dan Stoza6b9454d2014-11-07 16:00:59 -08001508bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001510 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001511}
1512
1513void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001514 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001515
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001516 mRefreshPending = false;
1517
Pablo Ceballos40845df2016-01-25 17:41:15 -08001518 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001519
Brian Andersond6927fb2016-07-23 23:37:30 -07001520 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001521 rebuildLayerStacks();
1522 setUpHWComposer();
1523 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001524 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001525 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001526 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001527
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001528 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001529
1530 mHadClientComposition = false;
1531 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1532 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1533 mHadClientComposition = mHadClientComposition ||
1534 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1535 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001536
Dan Stoza9e56aa02015-11-02 13:00:03 -08001537 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001538}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001539
Mathias Agopiancd60f992012-08-16 16:28:27 -07001540void SurfaceFlinger::doDebugFlashRegions()
1541{
1542 // is debugging enabled
1543 if (CC_LIKELY(!mDebugRegion))
1544 return;
1545
1546 const bool repaintEverything = mRepaintEverything;
1547 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1548 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001549 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001550 // transform the dirty region into this screen's coordinate space
1551 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1552 if (!dirtyRegion.isEmpty()) {
1553 // redraw the whole screen
1554 doComposeSurfaces(hw, Region(hw->bounds()));
1555
1556 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001558 RenderEngine& engine(getRenderEngine());
1559 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1560
Mathias Agopianda27af92012-09-13 18:17:13 -07001561 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001562 }
1563 }
1564 }
1565
1566 postFramebuffer();
1567
1568 if (mDebugRegion > 1) {
1569 usleep(mDebugRegion * 1000);
1570 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001571
Dan Stoza9e56aa02015-11-02 13:00:03 -08001572 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001573 auto& displayDevice = mDisplays[displayId];
1574 if (!displayDevice->isDisplayOn()) {
1575 continue;
1576 }
1577
1578 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001579 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1580 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001581 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582}
1583
Adrian Roos1e1a1282017-11-01 19:05:31 +01001584void SurfaceFlinger::doTracing(const char* where) {
1585 ATRACE_CALL();
1586 ATRACE_NAME(where);
1587 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001588 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001589 }
1590}
1591
Brian Andersond6927fb2016-07-23 23:37:30 -07001592void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001593{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001594 ATRACE_CALL();
1595 ALOGV("preComposition");
1596
Mathias Agopiancd60f992012-08-16 16:28:27 -07001597 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001598 mDrawingState.traverseInZOrder([&](Layer* layer) {
1599 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001600 needExtraInvalidate = true;
1601 }
Robert Carr2047fae2016-11-28 14:09:09 -08001602 });
1603
Mathias Agopiancd60f992012-08-16 16:28:27 -07001604 if (needExtraInvalidate) {
1605 signalLayerUpdate();
1606 }
1607}
1608
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001609void SurfaceFlinger::updateCompositorTiming(
1610 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1611 std::shared_ptr<FenceTime>& presentFenceTime) {
1612 // Update queue of past composite+present times and determine the
1613 // most recently known composite to present latency.
1614 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1615 nsecs_t compositeToPresentLatency = -1;
1616 while (!mCompositePresentTimes.empty()) {
1617 CompositePresentTime& cpt = mCompositePresentTimes.front();
1618 // Cached values should have been updated before calling this method,
1619 // which helps avoid duplicate syscalls.
1620 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1621 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1622 break;
1623 }
1624 compositeToPresentLatency = displayTime - cpt.composite;
1625 mCompositePresentTimes.pop();
1626 }
1627
1628 // Don't let mCompositePresentTimes grow unbounded, just in case.
1629 while (mCompositePresentTimes.size() > 16) {
1630 mCompositePresentTimes.pop();
1631 }
1632
Brian Andersond0010582017-03-07 13:20:31 -08001633 setCompositorTimingSnapped(
1634 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1635}
1636
1637void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1638 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001639 // Integer division and modulo round toward 0 not -inf, so we need to
1640 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001641 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1643 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1644
Brian Andersond0010582017-03-07 13:20:31 -08001645 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1646 if (idealLatency <= 0) {
1647 idealLatency = vsyncInterval;
1648 }
1649
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650 // Snap the latency to a value that removes scheduling jitter from the
1651 // composition and present times, which often have >1ms of jitter.
1652 // Reducing jitter is important if an app attempts to extrapolate
1653 // something (such as user input) to an accurate diasplay time.
1654 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1655 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001656 nsecs_t bias = vsyncInterval / 2;
1657 int64_t extraVsyncs =
1658 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1659 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1660 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001661
Brian Andersond0010582017-03-07 13:20:31 -08001662 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001663 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1664 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001665 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001666}
1667
1668void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001669{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001670 ATRACE_CALL();
1671 ALOGV("postComposition");
1672
Brian Anderson3546a3f2016-07-14 11:51:14 -07001673 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001674 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001675 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001676 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001677 }
1678
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001679 // |mStateLock| not needed as we are on the main thread
1680 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001681
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001682 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001683 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1684 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1685 glCompositionDoneFenceTime =
1686 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1687 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1688 } else {
1689 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1690 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001691
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001692 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001693 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1694 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1695 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001696
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001697 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1698 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1699
1700 // We use the refreshStartTime which might be sampled a little later than
1701 // when we started doing work for this frame, but that should be okay
1702 // since updateCompositorTiming has snapping logic.
1703 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001704 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001705 CompositorTiming compositorTiming;
1706 {
1707 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1708 compositorTiming = mCompositorTiming;
1709 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001710
Robert Carr2047fae2016-11-28 14:09:09 -08001711 mDrawingState.traverseInZOrder([&](Layer* layer) {
1712 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001713 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001714 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001715 recordBufferingStats(layer->getName().string(),
1716 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001717 }
Robert Carr2047fae2016-11-28 14:09:09 -08001718 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001719
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001720 if (presentFenceTime->isValid()) {
1721 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001722 enableHardwareVsync();
1723 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001724 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001725 }
1726 }
1727
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001728 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001729 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001730 enableHardwareVsync();
1731 }
1732 }
1733
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001734 if (mAnimCompositionPending) {
1735 mAnimCompositionPending = false;
1736
Brian Anderson4e606e32017-03-16 15:34:57 -07001737 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001738 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001739 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001740 } else {
1741 // The HWC doesn't support present fences, so use the refresh
1742 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001743 nsecs_t presentTime =
1744 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001745 mAnimFrameTracker.setActualPresentTime(presentTime);
1746 }
1747 mAnimFrameTracker.advanceFrame();
1748 }
Dan Stozab90cf072015-03-05 11:05:59 -08001749
1750 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1751 return;
1752 }
1753
1754 nsecs_t currentTime = systemTime();
1755 if (mHasPoweredOff) {
1756 mHasPoweredOff = false;
1757 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001758 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001759 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001760 if (numPeriods < NUM_BUCKETS - 1) {
1761 mFrameBuckets[numPeriods] += elapsedTime;
1762 } else {
1763 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1764 }
1765 mTotalTime += elapsedTime;
1766 }
1767 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001768}
1769
1770void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001771 ATRACE_CALL();
1772 ALOGV("rebuildLayerStacks");
1773
Mathias Agopiancd60f992012-08-16 16:28:27 -07001774 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001775 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001776 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001777 mVisibleRegionsDirty = false;
1778 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001779
Jeff Sharkey76488112017-02-27 14:15:18 -07001780 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1781 Region opaqueRegion;
1782 Region dirtyRegion;
1783 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001784 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001785 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1786 const Transform& tr(displayDevice->getTransform());
1787 const Rect bounds(displayDevice->getBounds());
1788 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001789 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001790
Jeff Sharkey76488112017-02-27 14:15:18 -07001791 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001792 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001793 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1794 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001795 Region drawRegion(tr.transform(
1796 layer->visibleNonTransparentRegion));
1797 drawRegion.andSelf(bounds);
1798 if (!drawRegion.isEmpty()) {
1799 layersSortedByZ.add(layer);
1800 } else {
1801 // Clear out the HWC layer if this layer was
1802 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001803 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001804 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001805 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001806 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001807 // WM changes displayDevice->layerStack upon sleep/awake.
1808 // Here we make sure we delete the HWC layers even if
1809 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001810 hwcLayerDestroyed = layer->destroyHwcLayer(
1811 displayDevice->getHwcDisplayId());
1812 }
1813
1814 // If a layer is not going to get a release fence because
1815 // it is invisible, but it is also going to release its
1816 // old buffer, add it to the list of layers needing
1817 // fences.
1818 if (hwcLayerDestroyed) {
1819 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1820 mLayersWithQueuedFrames.cend(), layer);
1821 if (found != mLayersWithQueuedFrames.cend()) {
1822 layersNeedingFences.add(layer);
1823 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001824 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001825 });
1826 }
1827 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001828 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001829 displayDevice->undefinedRegion.set(bounds);
1830 displayDevice->undefinedRegion.subtractSelf(
1831 tr.transform(opaqueRegion));
1832 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001833 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001834 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001835}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001836
Romain Guy0147a172017-06-01 13:53:56 -07001837mat4 SurfaceFlinger::computeSaturationMatrix() const {
1838 if (mSaturation == 1.0f) {
1839 return mat4();
1840 }
1841
1842 // Rec.709 luma coefficients
1843 float3 luminance{0.213f, 0.715f, 0.072f};
1844 luminance *= 1.0f - mSaturation;
1845 return mat4(
1846 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1847 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1848 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1849 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1850 );
1851}
1852
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001853// pickColorMode translates a given dataspace into the best available color mode.
1854// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001855android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001856 if (mForceNativeColorMode) {
1857 return HAL_COLOR_MODE_NATIVE;
1858 }
1859
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001860 switch (dataSpace) {
1861 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1862 // system expects.
1863 case HAL_DATASPACE_UNKNOWN:
1864 case HAL_DATASPACE_SRGB:
1865 case HAL_DATASPACE_V0_SRGB:
1866 return HAL_COLOR_MODE_SRGB;
1867 break;
1868
1869 case HAL_DATASPACE_DISPLAY_P3:
1870 return HAL_COLOR_MODE_DISPLAY_P3;
1871 break;
1872
1873 default:
1874 // TODO (courtneygo): Do we want to assert an error here?
1875 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1876 dataSpace);
1877 return HAL_COLOR_MODE_SRGB;
1878 break;
1879 }
1880}
1881
Romain Guy0147a172017-06-01 13:53:56 -07001882android_dataspace SurfaceFlinger::bestTargetDataSpace(
1883 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001884 // Only support sRGB and Display-P3 right now.
1885 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1886 return HAL_DATASPACE_DISPLAY_P3;
1887 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001888 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1889 return HAL_DATASPACE_DISPLAY_P3;
1890 }
1891 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1892 return HAL_DATASPACE_DISPLAY_P3;
1893 }
1894
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001895 return HAL_DATASPACE_V0_SRGB;
1896}
1897
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001899 ATRACE_CALL();
1900 ALOGV("setUpHWComposer");
1901
Jesse Hall028dc8f2013-08-20 16:35:32 -07001902 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001903 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1904 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1905 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1906
1907 // If nothing has changed (!dirty), don't recompose.
1908 // If something changed, but we don't currently have any visible layers,
1909 // and didn't when we last did a composition, then skip it this time.
1910 // The second rule does two things:
1911 // - When all layers are removed from a display, we'll emit one black
1912 // frame, then nothing more until we get new layers.
1913 // - When a display is created with a private layer stack, we won't
1914 // emit any black frames until a layer is added to the layer stack.
1915 bool mustRecompose = dirty && !(empty && wasEmpty);
1916
1917 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1918 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1919 mustRecompose ? "doing" : "skipping",
1920 dirty ? "+" : "-",
1921 empty ? "+" : "-",
1922 wasEmpty ? "+" : "-");
1923
Dan Stoza71433162014-02-04 16:22:36 -08001924 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001925
1926 if (mustRecompose) {
1927 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1928 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001929 }
1930
Dan Stoza9e56aa02015-11-02 13:00:03 -08001931 // build the h/w work list
1932 if (CC_UNLIKELY(mGeometryInvalid)) {
1933 mGeometryInvalid = false;
1934 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1935 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1936 const auto hwcId = displayDevice->getHwcDisplayId();
1937 if (hwcId >= 0) {
1938 const Vector<sp<Layer>>& currentLayers(
1939 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001940 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001941 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001942 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001943 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001944 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001945 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001946 }
1947 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001948
Robert Carrae060832016-11-28 10:51:00 -08001949 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001950 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001952 }
1953 }
1954 }
1955 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 }
Riley Andrews03414a12014-07-01 14:22:59 -07001957
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001958
Romain Guy0147a172017-06-01 13:53:56 -07001959 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001960
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 // Set the per-frame data
1962 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1963 auto& displayDevice = mDisplays[displayId];
1964 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001965
Dan Stoza9e56aa02015-11-02 13:00:03 -08001966 if (hwcId < 0) {
1967 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001968 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001969 if (colorMatrix != mPreviousColorMatrix) {
1970 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1971 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1972 "display %zd: %d", displayId, result);
1973 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
chaviwc9232ed2017-11-14 15:31:15 -08001975 if (layer->getForceClientComposition(hwcId)) {
1976 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1977 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1978 continue;
1979 }
1980
Dan Stoza9e56aa02015-11-02 13:00:03 -08001981 layer->setPerFrameData(displayDevice);
1982 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001983
1984 if (hasWideColorDisplay) {
1985 android_color_mode newColorMode;
1986 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1987
1988 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1989 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1990 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1991 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1992 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1993 }
1994 newColorMode = pickColorMode(newDataSpace);
1995
Thierry Strudel2924d012017-08-14 15:19:37 -07001996 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001997 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001998 }
1999
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002000 mPreviousColorMatrix = colorMatrix;
2001
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002003 auto& displayDevice = mDisplays[displayId];
2004 if (!displayDevice->isDisplayOn()) {
2005 continue;
2006 }
2007
2008 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002009 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2010 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002011 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002012}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002013
Mathias Agopiancd60f992012-08-16 16:28:27 -07002014void SurfaceFlinger::doComposition() {
2015 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002016 ALOGV("doComposition");
2017
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002018 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002019 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002020 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002021 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002022 // transform the dirty region into this screen's coordinate space
2023 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002024
2025 // repaint the framebuffer (if needed)
2026 doDisplayComposition(hw, dirtyRegion);
2027
Mathias Agopiancd60f992012-08-16 16:28:27 -07002028 hw->dirtyRegion.clear();
2029 hw->flip(hw->swapRegion);
2030 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07002031 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002032 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002033 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002034}
2035
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002036void SurfaceFlinger::postFramebuffer()
2037{
Mathias Agopian841cde52012-03-01 15:44:37 -08002038 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002039 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002040
Mathias Agopiana44b0412011-10-16 18:46:35 -07002041 const nsecs_t now = systemTime();
2042 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002043
Dan Stoza9e56aa02015-11-02 13:00:03 -08002044 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2045 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002046 if (!displayDevice->isDisplayOn()) {
2047 continue;
2048 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002049 const auto hwcId = displayDevice->getHwcDisplayId();
2050 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002051 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002052 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002053 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002054 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002055 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002056 // The layer buffer from the previous frame (if any) is released
2057 // by HWC only when the release fence from this frame (if any) is
2058 // signaled. Always get the release fence from HWC first.
2059 auto hwcLayer = layer->getHwcLayer(hwcId);
2060 sp<Fence> releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2061
2062 // If the layer was client composited in the previous frame, we
2063 // need to merge with the previous client target acquire fence.
2064 // Since we do not track that, always merge with the current
2065 // client target acquire fence when it is available, even though
2066 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002068 releaseFence = Fence::merge("LayerRelease", releaseFence,
2069 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002070 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002071
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 layer->onLayerDisplayed(releaseFence);
2073 }
Chia-I Wu83806892017-11-16 10:50:20 -08002074
2075 // We've got a list of layers needing fences, that are disjoint with
2076 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2077 // supply them with the present fence.
2078 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
2079 sp<Fence> presentFence = mHwc->getPresentFence(hwcId);
2080 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2081 layer->onLayerDisplayed(presentFence);
2082 }
2083 }
2084
Dan Stoza9e56aa02015-11-02 13:00:03 -08002085 if (hwcId >= 0) {
2086 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002087 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002088 }
2089
Mathias Agopiana44b0412011-10-16 18:46:35 -07002090 mLastSwapBufferTime = systemTime() - now;
2091 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002092
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002093 // |mStateLock| not needed as we are on the main thread
2094 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002095 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2096 logFrameStats();
2097 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002098}
2099
Mathias Agopian87baae12012-07-31 12:38:26 -07002100void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002101{
Mathias Agopian841cde52012-03-01 15:44:37 -08002102 ATRACE_CALL();
2103
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002104 // here we keep a copy of the drawing state (that is the state that's
2105 // going to be overwritten by handleTransactionLocked()) outside of
2106 // mStateLock so that the side-effects of the State assignment
2107 // don't happen with mStateLock held (which can cause deadlocks).
2108 State drawingState(mDrawingState);
2109
Mathias Agopianca4d3602011-05-19 15:38:14 -07002110 Mutex::Autolock _l(mStateLock);
2111 const nsecs_t now = systemTime();
2112 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002113
Mathias Agopianca4d3602011-05-19 15:38:14 -07002114 // Here we're guaranteed that some transaction flags are set
2115 // so we can call handleTransactionLocked() unconditionally.
2116 // We call getTransactionFlags(), which will also clear the flags,
2117 // with mStateLock held to guarantee that mCurrentState won't change
2118 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002119
Mathias Agopiane57f2922012-08-09 16:29:12 -07002120 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002121 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002122
Mathias Agopianca4d3602011-05-19 15:38:14 -07002123 mLastTransactionTime = systemTime() - now;
2124 mDebugInTransaction = 0;
2125 invalidateHwcGeometry();
2126 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002127}
2128
Mathias Agopian87baae12012-07-31 12:38:26 -07002129void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002130{
Dan Stoza7dde5992015-05-22 09:51:44 -07002131 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002132 mCurrentState.traverseInZOrder([](Layer* layer) {
2133 layer->notifyAvailableFrames();
2134 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002135
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002136 /*
2137 * Traversal of the children
2138 * (perform the transaction for each of them if needed)
2139 */
2140
Mathias Agopian3559b072012-08-15 13:46:03 -07002141 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002142 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002143 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002144 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002145
2146 const uint32_t flags = layer->doTransaction(0);
2147 if (flags & Layer::eVisibleRegion)
2148 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002149 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002150 }
2151
2152 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002153 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002154 */
2155
Mathias Agopiane57f2922012-08-09 16:29:12 -07002156 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002157 // here we take advantage of Vector's copy-on-write semantics to
2158 // improve performance by skipping the transaction entirely when
2159 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002160 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2161 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002162 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002163 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002164 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002165 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002166
2167 // find the displays that were removed
2168 // (ie: in drawing state but not in current state)
2169 // also handle displays that changed
2170 // (ie: displays that are in both lists)
2171 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002172 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2173 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002174 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002175 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002176 // Call makeCurrent() on the primary display so we can
2177 // be sure that nothing associated with this display
2178 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002179 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002180 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002181 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002182 if (hw != NULL)
2183 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002184 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002185 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002186 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002187 } else {
2188 ALOGW("trying to remove the main display");
2189 }
2190 } else {
2191 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002192 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002193 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002194 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2195 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002196 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002197 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002198 // recreating the DisplayDevice, so we just remove it
2199 // from the drawing state, so that it get re-added
2200 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002201 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002202 if (hw != NULL)
2203 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002204 mDisplays.removeItem(display);
2205 mDrawingState.displays.removeItemsAt(i);
2206 dc--; i--;
2207 // at this point we must loop to the next item
2208 continue;
2209 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002210
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002211 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002212 if (disp != NULL) {
2213 if (state.layerStack != draw[i].layerStack) {
2214 disp->setLayerStack(state.layerStack);
2215 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002216 if ((state.orientation != draw[i].orientation)
2217 || (state.viewport != draw[i].viewport)
2218 || (state.frame != draw[i].frame))
2219 {
2220 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002221 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002222 }
Michael Lentine47e45402014-07-18 15:34:25 -07002223 if (state.width != draw[i].width || state.height != draw[i].height) {
2224 disp->setDisplaySize(state.width, state.height);
2225 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002226 }
2227 }
2228 }
2229
2230 // find displays that were added
2231 // (ie: in current state but not in drawing state)
2232 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002233 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002234 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002235
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002236 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002237 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002238 sp<IGraphicBufferProducer> bqProducer;
2239 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002240 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002241
Dan Stoza9e56aa02015-11-02 13:00:03 -08002242 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002243 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002244 // Virtual displays without a surface are dormant:
2245 // they have external state (layer stack, projection,
2246 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002247 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002248
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002249 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002250 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002251 int width = 0;
2252 int status = state.surface->query(
2253 NATIVE_WINDOW_WIDTH, &width);
2254 ALOGE_IF(status != NO_ERROR,
2255 "Unable to query width (%d)", status);
2256 int height = 0;
2257 status = state.surface->query(
2258 NATIVE_WINDOW_HEIGHT, &height);
2259 ALOGE_IF(status != NO_ERROR,
2260 "Unable to query height (%d)", status);
2261 int intFormat = 0;
2262 status = state.surface->query(
2263 NATIVE_WINDOW_FORMAT, &intFormat);
2264 ALOGE_IF(status != NO_ERROR,
2265 "Unable to query format (%d)", status);
2266 auto format = static_cast<android_pixel_format_t>(
2267 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002268
Dan Stoza8cf150a2016-08-02 10:27:31 -07002269 mHwc->allocateVirtualDisplay(width, height, &format,
2270 &hwcId);
2271 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002272
Dan Stoza5cf424b2016-05-20 14:02:39 -07002273 // TODO: Plumb requested format back up to consumer
2274
Dan Stoza9e56aa02015-11-02 13:00:03 -08002275 sp<VirtualDisplaySurface> vds =
2276 new VirtualDisplaySurface(*mHwc,
2277 hwcId, state.surface, bqProducer,
2278 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002279
2280 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002281 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002282 }
2283 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002284 ALOGE_IF(state.surface!=NULL,
2285 "adding a supported display, but rendering "
2286 "surface is provided (%p), ignoring it",
2287 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002288
2289 hwcId = state.type;
2290 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2291 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002292 }
2293
2294 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002295 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002296 sp<DisplayDevice> hw =
2297 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2298 dispSurface, producer,
2299 mRenderEngine->getEGLConfig(),
2300 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002301 hw->setLayerStack(state.layerStack);
2302 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002303 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002304 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002305 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002306 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002307 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002308 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002309 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002310 }
2311 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002312 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002313 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002314
Mathias Agopian84300952012-11-21 16:02:13 -08002315 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2316 // The transform hint might have changed for some layers
2317 // (either because a display has changed, or because a layer
2318 // as changed).
2319 //
2320 // Walk through all the layers in currentLayers,
2321 // and update their transform hint.
2322 //
2323 // If a layer is visible only on a single display, then that
2324 // display is used to calculate the hint, otherwise we use the
2325 // default display.
2326 //
2327 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2328 // the hint is set before we acquire a buffer from the surface texture.
2329 //
2330 // NOTE: layer transactions have taken place already, so we use their
2331 // drawing state. However, SurfaceFlinger's own transaction has not
2332 // happened yet, so we must use the current state layer list
2333 // (soon to become the drawing state list).
2334 //
2335 sp<const DisplayDevice> disp;
2336 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002337 bool first = true;
2338 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002339 // NOTE: we rely on the fact that layers are sorted by
2340 // layerStack first (so we don't have to traverse the list
2341 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002342 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002343 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002344 currentlayerStack = layerStack;
2345 // figure out if this layerstack is mirrored
2346 // (more than one display) if so, pick the default display,
2347 // if not, pick the only display it's on.
2348 disp.clear();
2349 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2350 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002351 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002352 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002353 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002354 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002355 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002356 break;
2357 }
2358 }
2359 }
2360 }
Chet Haase91d25932013-04-11 15:24:55 -07002361 if (disp == NULL) {
2362 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2363 // redraw after transform hint changes. See bug 8508397.
2364
2365 // could be null when this layer is using a layerStack
2366 // that is not visible on any display. Also can occur at
2367 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002368 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002369 }
Chet Haase91d25932013-04-11 15:24:55 -07002370 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002371
2372 first = false;
2373 });
Mathias Agopian84300952012-11-21 16:02:13 -08002374 }
2375
2376
Mathias Agopian3559b072012-08-15 13:46:03 -07002377 /*
2378 * Perform our own transaction if needed
2379 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002380
2381 if (mLayersAdded) {
2382 mLayersAdded = false;
2383 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002384 mVisibleRegionsDirty = true;
2385 }
2386
2387 // some layers might have been removed, so
2388 // we need to update the regions they're exposing.
2389 if (mLayersRemoved) {
2390 mLayersRemoved = false;
2391 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002392 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002393 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002394 // this layer is not visible anymore
2395 // TODO: we could traverse the tree from front to back and
2396 // compute the actual visible region
2397 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002398 Region visibleReg;
2399 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002400 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002401 }
Robert Carr2047fae2016-11-28 14:09:09 -08002402 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002403 }
2404
2405 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002406
2407 updateCursorAsync();
2408}
2409
2410void SurfaceFlinger::updateCursorAsync()
2411{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002412 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2413 auto& displayDevice = mDisplays[displayId];
2414 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002415 continue;
2416 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002417
2418 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2419 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002420 }
2421 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002422}
2423
2424void SurfaceFlinger::commitTransaction()
2425{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002426 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002427 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002428 for (const auto& l : mLayersPendingRemoval) {
2429 recordBufferingStats(l->getName().string(),
2430 l->getOccupancyHistory(true));
2431 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002432 }
2433 mLayersPendingRemoval.clear();
2434 }
2435
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002436 // If this transaction is part of a window animation then the next frame
2437 // we composite should be considered an animation as well.
2438 mAnimCompositionPending = mAnimTransactionPending;
2439
Mathias Agopian4fec8732012-06-29 14:12:52 -07002440 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002441 mDrawingState.traverseInZOrder([](Layer* layer) {
2442 layer->commitChildList();
2443 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002444 mTransactionPending = false;
2445 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002446 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002447}
2448
Chia-I Wuab0c3192017-08-01 11:29:00 -07002449void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002450 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002451{
Mathias Agopian841cde52012-03-01 15:44:37 -08002452 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002453 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002454
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455 Region aboveOpaqueLayers;
2456 Region aboveCoveredLayers;
2457 Region dirty;
2458
Mathias Agopian87baae12012-07-31 12:38:26 -07002459 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002460
Robert Carr2047fae2016-11-28 14:09:09 -08002461 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002462 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002463 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002464
Jesse Hall01e29052013-02-19 16:13:35 -08002465 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002466 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002467 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002468
Mathias Agopianab028732010-03-16 16:41:46 -07002469 /*
2470 * opaqueRegion: area of a surface that is fully opaque.
2471 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002472 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002473
2474 /*
2475 * visibleRegion: area of a surface that is visible on screen
2476 * and not fully transparent. This is essentially the layer's
2477 * footprint minus the opaque regions above it.
2478 * Areas covered by a translucent surface are considered visible.
2479 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002481
2482 /*
2483 * coveredRegion: area of a surface that is covered by all
2484 * visible regions above it (which includes the translucent areas).
2485 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002487
Jesse Halla8026d22012-09-25 13:25:04 -07002488 /*
2489 * transparentRegion: area of a surface that is hinted to be completely
2490 * transparent. This is only used to tell when the layer has no visible
2491 * non-transparent regions and can be removed from the layer list. It
2492 * does not affect the visibleRegion of this layer or any layers
2493 * beneath it. The hint may not be correct if apps don't respect the
2494 * SurfaceView restrictions (which, sadly, some don't).
2495 */
2496 Region transparentRegion;
2497
Mathias Agopianab028732010-03-16 16:41:46 -07002498
2499 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002500 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002501 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002502 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002504 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002505 if (!visibleRegion.isEmpty()) {
2506 // Remove the transparent area from the visible region
2507 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002508 if (tr.preserveRects()) {
2509 // transform the transparent region
2510 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002511 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002512 // transformation too complex, can't do the
2513 // transparent region optimization.
2514 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002515 }
Mathias Agopianab028732010-03-16 16:41:46 -07002516 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517
Mathias Agopianab028732010-03-16 16:41:46 -07002518 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002519 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002520 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002521 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2522 // the opaque region is the layer's footprint
2523 opaqueRegion = visibleRegion;
2524 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002525 }
2526 }
2527
Mathias Agopianab028732010-03-16 16:41:46 -07002528 // Clip the covered region to the visible region
2529 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2530
2531 // Update aboveCoveredLayers for next (lower) layer
2532 aboveCoveredLayers.orSelf(visibleRegion);
2533
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002534 // subtract the opaque region covered by the layers above us
2535 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536
2537 // compute this layer's dirty region
2538 if (layer->contentDirty) {
2539 // we need to invalidate the whole region
2540 dirty = visibleRegion;
2541 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002542 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543 layer->contentDirty = false;
2544 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002545 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002546 * the exposed region consists of two components:
2547 * 1) what's VISIBLE now and was COVERED before
2548 * 2) what's EXPOSED now less what was EXPOSED before
2549 *
2550 * note that (1) is conservative, we start with the whole
2551 * visible region but only keep what used to be covered by
2552 * something -- which mean it may have been exposed.
2553 *
2554 * (2) handles areas that were not covered by anything but got
2555 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002556 */
Mathias Agopianab028732010-03-16 16:41:46 -07002557 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002558 const Region oldVisibleRegion = layer->visibleRegion;
2559 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002560 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2561 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562 }
2563 dirty.subtractSelf(aboveOpaqueLayers);
2564
2565 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002566 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567
Mathias Agopianab028732010-03-16 16:41:46 -07002568 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002570
Jesse Halla8026d22012-09-25 13:25:04 -07002571 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 layer->setVisibleRegion(visibleRegion);
2573 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002574 layer->setVisibleNonTransparentRegion(
2575 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002576 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577
Mathias Agopian87baae12012-07-31 12:38:26 -07002578 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579}
2580
Chia-I Wuab0c3192017-08-01 11:29:00 -07002581void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002582 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002583 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002584 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002585 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002586 }
2587 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002588}
2589
Dan Stoza6b9454d2014-11-07 16:00:59 -08002590bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002592 ALOGV("handlePageFlip");
2593
Brian Andersond6927fb2016-07-23 23:37:30 -07002594 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595
Mathias Agopian4fec8732012-06-29 14:12:52 -07002596 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002597 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002598 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002599
2600 // Store the set of layers that need updates. This set must not change as
2601 // buffers are being latched, as this could result in a deadlock.
2602 // Example: Two producers share the same command stream and:
2603 // 1.) Layer 0 is latched
2604 // 2.) Layer 0 gets a new frame
2605 // 2.) Layer 1 gets a new frame
2606 // 3.) Layer 1 is latched.
2607 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2608 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002609 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002610 if (layer->hasQueuedFrame()) {
2611 frameQueued = true;
2612 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002613 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002614 } else {
2615 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002616 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002617 } else {
2618 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002619 }
Robert Carr2047fae2016-11-28 14:09:09 -08002620 });
2621
Dan Stoza9e56aa02015-11-02 13:00:03 -08002622 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002623 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002624 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002625 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002626 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002627 newDataLatched = true;
2628 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002629 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002630
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002631 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002632
2633 // If we will need to wake up at some time in the future to deal with a
2634 // queued frame that shouldn't be displayed during this vsync period, wake
2635 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002636 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002637 signalLayerUpdate();
2638 }
2639
2640 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002641 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642}
2643
Mathias Agopianad456f92011-01-13 17:53:01 -08002644void SurfaceFlinger::invalidateHwcGeometry()
2645{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002646 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002647}
2648
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002649
Fabien Sanglard830b8472016-11-30 16:35:58 -08002650void SurfaceFlinger::doDisplayComposition(
2651 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002652 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653{
Dan Stoza71433162014-02-04 16:22:36 -08002654 // We only need to actually compose the display if:
2655 // 1) It is being handled by hardware composer, which may need this to
2656 // keep its virtual display state machine in sync, or
2657 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002658 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002659 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002660 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002661 return;
2662 }
2663
Dan Stoza9e56aa02015-11-02 13:00:03 -08002664 ALOGV("doDisplayComposition");
2665
Mathias Agopian87baae12012-07-31 12:38:26 -07002666 Region dirtyRegion(inDirtyRegion);
2667
Mathias Agopianb8a55602009-06-26 19:06:36 -07002668 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002669 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002670
Fabien Sanglard830b8472016-11-30 16:35:58 -08002671 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002672 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002673 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2674 // takes a rectangle, we must make sure to update that whole
2675 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002676 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002677 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002678 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002679 // We need to redraw the rectangle that will be updated
2680 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002681 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002682 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002683 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002684 } else {
2685 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002686 dirtyRegion.set(displayDevice->bounds());
2687 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002688 }
2689 }
2690
Fabien Sanglard830b8472016-11-30 16:35:58 -08002691 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002692
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002693 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002694 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002695
2696 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002697 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698}
2699
Dan Stoza9e56aa02015-11-02 13:00:03 -08002700bool SurfaceFlinger::doComposeSurfaces(
2701 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002702{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002703 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002704
chaviwa76b2712017-09-20 12:02:26 -07002705 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002706 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002707
2708 mat4 oldColorMatrix;
2709 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2710 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2711 if (applyColorMatrix) {
2712 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2713 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2714 }
2715
Dan Stoza9e56aa02015-11-02 13:00:03 -08002716 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2717 if (hasClientComposition) {
2718 ALOGV("hasClientComposition");
2719
Romain Guy54f154a2017-10-24 21:40:32 +01002720 mRenderEngine->setWideColor(
2721 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2722 mRenderEngine->setColorMode(mForceNativeColorMode ?
2723 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002724 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002725 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002726 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002727 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002728
2729 // |mStateLock| not needed as we are on the main thread
2730 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002731 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2732 }
2733 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002734 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002735
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002736 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002737 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2738 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002739 // when using overlays, we assume a fully transparent framebuffer
2740 // NOTE: we could reduce how much we need to clear, for instance
2741 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002742 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002743 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002744 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002745 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002746 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002747 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002748
2749 // we remove the scissor part
2750 // we're left with the letterbox region
2751 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002753
2754 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002755 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002756
2757 // but limit it to the dirty region
2758 region.andSelf(dirty);
2759
Mathias Agopianb9494d52012-04-18 02:28:45 -07002760 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002761 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002762 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002763 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002764 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002765 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002766
Dan Stoza9e56aa02015-11-02 13:00:03 -08002767 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002768 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002769 // scissor on the main display. It should never be needed
2770 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 const Rect& bounds(displayDevice->getBounds());
2772 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002773 if (scissor != bounds) {
2774 // scissor doesn't match the screen's dimensions, so we
2775 // need to clear everything outside of it and enable
2776 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002777
Mathias Agopianf45c5102012-10-24 16:29:17 -07002778 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002779 const uint32_t height = displayDevice->getHeight();
2780 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002781 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002782 }
2783 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002784 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002785
Mathias Agopian85d751c2012-08-29 16:59:24 -07002786 /*
2787 * and then, render the layers targeted at the framebuffer
2788 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002789
Dan Stoza9e56aa02015-11-02 13:00:03 -08002790 ALOGV("Rendering client layers");
2791 const Transform& displayTransform = displayDevice->getTransform();
2792 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002793 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002794 bool firstLayer = true;
2795 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2796 const Region clip(dirty.intersect(
2797 displayTransform.transform(layer->visibleRegion)));
2798 ALOGV("Layer: %s", layer->getName().string());
2799 ALOGV(" Composition type: %s",
2800 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002801 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002802 switch (layer->getCompositionType(hwcId)) {
2803 case HWC2::Composition::Cursor:
2804 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002805 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002806 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002807 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002808 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002809 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002810 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002811 // never clear the very first layer since we're
2812 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002813 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002814 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002815 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002816 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002817 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002818 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002819 break;
2820 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002821 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002822 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002823 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002824 } else {
2825 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002826 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002827 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002828 }
2829 } else {
2830 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002831 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002832 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002833 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002834 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002835 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002836 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002837 }
2838 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002839
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002840 if (applyColorMatrix) {
2841 getRenderEngine().setupColorTransform(oldColorMatrix);
2842 }
2843
Mathias Agopianf45c5102012-10-24 16:29:17 -07002844 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002846 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847}
2848
Fabien Sanglard830b8472016-11-30 16:35:58 -08002849void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2850 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002851 RenderEngine& engine(getRenderEngine());
2852 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853}
2854
Dan Stoza7d89d062015-04-30 13:29:25 -07002855status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002856 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002857 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002858 const sp<Layer>& lbc,
2859 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002860{
Dan Stoza7d89d062015-04-30 13:29:25 -07002861 // add this layer to the current state list
2862 {
2863 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002864 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002865 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2866 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002867 return NO_MEMORY;
2868 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002869 if (parent == nullptr) {
2870 mCurrentState.layersSortedByZ.add(lbc);
2871 } else {
chaviwc9674332017-08-28 12:32:18 -07002872 bool found = false;
2873 mCurrentState.traverseInZOrder([&](Layer* layer) {
2874 if (layer == parent.get()) {
2875 found = true;
2876 }
2877 });
2878
2879 if (!found) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002880 ALOGE("addClientLayer called with a removed parent");
2881 return NAME_NOT_FOUND;
2882 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883 parent->addChild(lbc);
2884 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002885
Dan Stoza7d89d062015-04-30 13:29:25 -07002886 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002887 mLayersAdded = true;
2888 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002889 }
2890
Mathias Agopian96f08192010-06-02 23:28:45 -07002891 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002892 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002893
Dan Stoza7d89d062015-04-30 13:29:25 -07002894 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002895}
2896
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002897status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002898 Mutex::Autolock _l(mStateLock);
2899
chaviw8b3871a2017-11-01 17:41:01 -07002900 if (layer->isPendingRemoval()) {
2901 return NO_ERROR;
2902 }
2903
Robert Carr1f0a16a2016-10-24 16:27:39 -07002904 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002905 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002906 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002907 if (topLevelOnly) {
2908 return NO_ERROR;
2909 }
2910
Chia-I Wu98f1c102017-05-30 14:54:08 -07002911 sp<Layer> ancestor = p;
2912 while (ancestor->getParent() != nullptr) {
2913 ancestor = ancestor->getParent();
2914 }
2915 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2916 ALOGE("removeLayer called with a layer whose parent has been removed");
2917 return NAME_NOT_FOUND;
2918 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002919
2920 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002921 } else {
2922 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002923 }
2924
Robert Carr136e2f62017-02-08 17:54:29 -08002925 // As a matter of normal operation, the LayerCleaner will produce a second
2926 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2927 // so we will succeed in promoting it, but it's already been removed
2928 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2929 // otherwise something has gone wrong and we are leaking the layer.
2930 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002931 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2932 layer->getName().string(),
2933 (p != nullptr) ? p->getName().string() : "no-parent");
2934 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002935 } else if (index < 0) {
2936 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002937 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002938
Chia-I Wuc6657022017-08-15 11:18:17 -07002939 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002940 mLayersPendingRemoval.add(layer);
2941 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002942 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002943 setTransactionFlags(eTransactionNeeded);
2944 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002945}
2946
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002947uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002948 return android_atomic_release_load(&mTransactionFlags);
2949}
2950
Mathias Agopian3f844832013-08-07 21:24:32 -07002951uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002952 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2953}
2954
Mathias Agopian3f844832013-08-07 21:24:32 -07002955uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2957 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002958 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959 }
2960 return old;
2961}
2962
Mathias Agopian8b33f032012-07-24 20:43:54 -07002963void SurfaceFlinger::setTransactionState(
2964 const Vector<ComposerState>& state,
2965 const Vector<DisplayState>& displays,
2966 uint32_t flags)
2967{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002968 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002969 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002970 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002971
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002972 if (flags & eAnimation) {
2973 // For window updates that are part of an animation we must wait for
2974 // previous animation "frames" to be handled.
2975 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002976 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002977 if (CC_UNLIKELY(err != NO_ERROR)) {
2978 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002979 // caller after a few seconds.
2980 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2981 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002982 mAnimTransactionPending = false;
2983 break;
2984 }
2985 }
2986 }
2987
Mathias Agopiane57f2922012-08-09 16:29:12 -07002988 size_t count = displays.size();
2989 for (size_t i=0 ; i<count ; i++) {
2990 const DisplayState& s(displays[i]);
2991 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002992 }
2993
Mathias Agopiane57f2922012-08-09 16:29:12 -07002994 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002995 for (size_t i=0 ; i<count ; i++) {
2996 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002997 // Here we need to check that the interface we're given is indeed
2998 // one of our own. A malicious client could give us a NULL
2999 // IInterface, or one of its own or even one of our own but a
3000 // different type. All these situations would cause us to crash.
3001 //
3002 // NOTE: it would be better to use RTTI as we could directly check
3003 // that we have a Client*. however, RTTI is disabled in Android.
3004 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003005 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003006 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08003007 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003008 sp<Client> client( static_cast<Client *>(s.client.get()) );
3009 transactionFlags |= setClientStateLocked(client, s.state);
3010 }
3011 }
3012 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003013 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003014
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003015 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3016 // anyway. This can be used as a flush mechanism for previous async transactions.
3017 // Empty animation transaction can be used to simulate back-pressure, so also force a
3018 // transaction for empty animation transactions.
3019 if (transactionFlags == 0 &&
3020 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003021 transactionFlags = eTransactionNeeded;
3022 }
3023
Mathias Agopian386aa982011-11-07 21:58:03 -08003024 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003025 if (mInterceptor.isEnabled()) {
3026 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
3027 }
Irvel468051e2016-06-13 16:44:44 -07003028
Mathias Agopian386aa982011-11-07 21:58:03 -08003029 // this triggers the transaction
3030 setTransactionFlags(transactionFlags);
3031
3032 // if this is a synchronous transaction, wait for it to take effect
3033 // before returning.
3034 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003035 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003036 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003037 if (flags & eAnimation) {
3038 mAnimTransactionPending = true;
3039 }
3040 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003041 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3042 if (CC_UNLIKELY(err != NO_ERROR)) {
3043 // just in case something goes wrong in SF, return to the
3044 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003045 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3046 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003047 break;
3048 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003049 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050 }
3051}
3052
Mathias Agopiane57f2922012-08-09 16:29:12 -07003053uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3054{
Jesse Hall9a143922012-10-04 16:29:19 -07003055 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3056 if (dpyIdx < 0)
3057 return 0;
3058
Mathias Agopiane57f2922012-08-09 16:29:12 -07003059 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003060 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003061 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003062 const uint32_t what = s.what;
3063 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003064 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003065 disp.surface = s.surface;
3066 flags |= eDisplayTransactionNeeded;
3067 }
3068 }
3069 if (what & DisplayState::eLayerStackChanged) {
3070 if (disp.layerStack != s.layerStack) {
3071 disp.layerStack = s.layerStack;
3072 flags |= eDisplayTransactionNeeded;
3073 }
3074 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003075 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003076 if (disp.orientation != s.orientation) {
3077 disp.orientation = s.orientation;
3078 flags |= eDisplayTransactionNeeded;
3079 }
3080 if (disp.frame != s.frame) {
3081 disp.frame = s.frame;
3082 flags |= eDisplayTransactionNeeded;
3083 }
3084 if (disp.viewport != s.viewport) {
3085 disp.viewport = s.viewport;
3086 flags |= eDisplayTransactionNeeded;
3087 }
3088 }
Michael Lentine47e45402014-07-18 15:34:25 -07003089 if (what & DisplayState::eDisplaySizeChanged) {
3090 if (disp.width != s.width) {
3091 disp.width = s.width;
3092 flags |= eDisplayTransactionNeeded;
3093 }
3094 if (disp.height != s.height) {
3095 disp.height = s.height;
3096 flags |= eDisplayTransactionNeeded;
3097 }
3098 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003099 }
3100 return flags;
3101}
3102
3103uint32_t SurfaceFlinger::setClientStateLocked(
3104 const sp<Client>& client,
3105 const layer_state_t& s)
3106{
Mathias Agopian13127d82013-03-05 17:47:11 -08003107 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003108 if (layer == nullptr) {
3109 return 0;
3110 }
3111
3112 if (layer->isPendingRemoval()) {
3113 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3114 return 0;
3115 }
3116
3117 uint32_t flags = 0;
3118
3119 const uint32_t what = s.what;
3120 bool geometryAppliesWithResize =
3121 what & layer_state_t::eGeometryAppliesWithResize;
3122 if (what & layer_state_t::ePositionChanged) {
3123 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3124 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003125 }
chaviw8b3871a2017-11-01 17:41:01 -07003126 }
3127 if (what & layer_state_t::eLayerChanged) {
3128 // NOTE: index needs to be calculated before we update the state
3129 const auto& p = layer->getParent();
3130 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003131 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003132 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003133 mCurrentState.layersSortedByZ.removeAt(idx);
3134 mCurrentState.layersSortedByZ.add(layer);
3135 // we need traversal (state changed)
3136 // AND transaction (list changed)
3137 flags |= eTransactionNeeded|eTraversalNeeded;
3138 }
chaviw8b3871a2017-11-01 17:41:01 -07003139 } else {
3140 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003141 flags |= eTransactionNeeded|eTraversalNeeded;
3142 }
3143 }
chaviw8b3871a2017-11-01 17:41:01 -07003144 }
3145 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003146 // NOTE: index needs to be calculated before we update the state
3147 const auto& p = layer->getParent();
3148 if (p == nullptr) {
3149 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3150 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3151 mCurrentState.layersSortedByZ.removeAt(idx);
3152 mCurrentState.layersSortedByZ.add(layer);
3153 // we need traversal (state changed)
3154 // AND transaction (list changed)
3155 flags |= eTransactionNeeded|eTraversalNeeded;
3156 }
3157 } else {
3158 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3159 flags |= eTransactionNeeded|eTraversalNeeded;
3160 }
chaviw8b3871a2017-11-01 17:41:01 -07003161 }
3162 }
3163 if (what & layer_state_t::eSizeChanged) {
3164 if (layer->setSize(s.w, s.h)) {
3165 flags |= eTraversalNeeded;
3166 }
3167 }
3168 if (what & layer_state_t::eAlphaChanged) {
3169 if (layer->setAlpha(s.alpha))
3170 flags |= eTraversalNeeded;
3171 }
3172 if (what & layer_state_t::eColorChanged) {
3173 if (layer->setColor(s.color))
3174 flags |= eTraversalNeeded;
3175 }
3176 if (what & layer_state_t::eMatrixChanged) {
3177 if (layer->setMatrix(s.matrix))
3178 flags |= eTraversalNeeded;
3179 }
3180 if (what & layer_state_t::eTransparentRegionChanged) {
3181 if (layer->setTransparentRegionHint(s.transparentRegion))
3182 flags |= eTraversalNeeded;
3183 }
3184 if (what & layer_state_t::eFlagsChanged) {
3185 if (layer->setFlags(s.flags, s.mask))
3186 flags |= eTraversalNeeded;
3187 }
3188 if (what & layer_state_t::eCropChanged) {
3189 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3190 flags |= eTraversalNeeded;
3191 }
3192 if (what & layer_state_t::eFinalCropChanged) {
3193 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3194 flags |= eTraversalNeeded;
3195 }
3196 if (what & layer_state_t::eLayerStackChanged) {
3197 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3198 // We only allow setting layer stacks for top level layers,
3199 // everything else inherits layer stack from its parent.
3200 if (layer->hasParent()) {
3201 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3202 layer->getName().string());
3203 } else if (idx < 0) {
3204 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3205 "that also does not appear in the top level layer list. Something"
3206 " has gone wrong.", layer->getName().string());
3207 } else if (layer->setLayerStack(s.layerStack)) {
3208 mCurrentState.layersSortedByZ.removeAt(idx);
3209 mCurrentState.layersSortedByZ.add(layer);
3210 // we need traversal (state changed)
3211 // AND transaction (list changed)
3212 flags |= eTransactionNeeded|eTraversalNeeded;
3213 }
3214 }
3215 if (what & layer_state_t::eDeferTransaction) {
3216 if (s.barrierHandle != nullptr) {
3217 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3218 } else if (s.barrierGbp != nullptr) {
3219 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3220 if (authenticateSurfaceTextureLocked(gbp)) {
3221 const auto& otherLayer =
3222 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3223 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3224 } else {
3225 ALOGE("Attempt to defer transaction to to an"
3226 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003227 }
3228 }
chaviw8b3871a2017-11-01 17:41:01 -07003229 // We don't trigger a traversal here because if no other state is
3230 // changed, we don't want this to cause any more work
3231 }
3232 if (what & layer_state_t::eReparent) {
3233 if (layer->reparent(s.parentHandleForChild)) {
3234 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003235 }
chaviw8b3871a2017-11-01 17:41:01 -07003236 }
3237 if (what & layer_state_t::eReparentChildren) {
3238 if (layer->reparentChildren(s.reparentHandle)) {
3239 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003240 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003241 }
chaviw8b3871a2017-11-01 17:41:01 -07003242 if (what & layer_state_t::eDetachChildren) {
3243 layer->detachChildren();
3244 }
3245 if (what & layer_state_t::eOverrideScalingModeChanged) {
3246 layer->setOverrideScalingMode(s.overrideScalingMode);
3247 // We don't trigger a traversal here because if no other state is
3248 // changed, we don't want this to cause any more work
3249 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003250 return flags;
3251}
3252
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003253status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003254 const String8& name,
3255 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003256 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003257 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3258 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003259{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003260 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003261 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003262 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003263 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003264 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003265
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003266 status_t result = NO_ERROR;
3267
3268 sp<Layer> layer;
3269
Cody Northropbc755282017-03-31 12:00:08 -06003270 String8 uniqueName = getUniqueLayerName(name);
3271
Mathias Agopian3165cc22012-08-08 19:42:09 -07003272 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3273 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003274 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003275 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003276 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003277
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278 break;
chaviw13fdc492017-06-27 12:40:18 -07003279 case ISurfaceComposerClient::eFXSurfaceColor:
3280 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003281 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003282 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003283 break;
3284 default:
3285 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286 break;
3287 }
3288
Dan Stoza7d89d062015-04-30 13:29:25 -07003289 if (result != NO_ERROR) {
3290 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003292
Chia-I Wuab0c3192017-08-01 11:29:00 -07003293 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3294 // TODO b/64227542
3295 if (windowType == 441731) {
3296 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3297 layer->setPrimaryDisplayOnly();
3298 }
3299
Albert Chaulk479c60c2017-01-27 14:21:34 -05003300 layer->setInfo(windowType, ownerUid);
3301
Robert Carr1f0a16a2016-10-24 16:27:39 -07003302 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003303 if (result != NO_ERROR) {
3304 return result;
3305 }
Irvelffc9efc2016-07-27 15:16:37 -07003306 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003307
3308 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003309 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003310}
3311
Cody Northropbc755282017-03-31 12:00:08 -06003312String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3313{
3314 bool matchFound = true;
3315 uint32_t dupeCounter = 0;
3316
3317 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3318 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3319
3320 // Loop over layers until we're sure there is no matching name
3321 while (matchFound) {
3322 matchFound = false;
3323 mDrawingState.traverseInZOrder([&](Layer* layer) {
3324 if (layer->getName() == uniqueName) {
3325 matchFound = true;
3326 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3327 }
3328 });
3329 }
3330
3331 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3332
3333 return uniqueName;
3334}
3335
David Sodman0c69cad2017-08-21 12:12:51 -07003336status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003337 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3338 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003339{
3340 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003341 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003342 case PIXEL_FORMAT_TRANSPARENT:
3343 case PIXEL_FORMAT_TRANSLUCENT:
3344 format = PIXEL_FORMAT_RGBA_8888;
3345 break;
3346 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003347 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003348 break;
3349 }
3350
David Sodman0c69cad2017-08-21 12:12:51 -07003351 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3352 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003353 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003354 *handle = layer->getHandle();
3355 *gbp = layer->getProducer();
3356 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003357 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003358
David Sodman0c69cad2017-08-21 12:12:51 -07003359 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003360 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003361}
3362
chaviw13fdc492017-06-27 12:40:18 -07003363status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003364 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003365 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366{
chaviw13fdc492017-06-27 12:40:18 -07003367 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003368 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003369 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003370}
3371
Mathias Agopianac9fa422013-02-11 16:40:36 -08003372status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003373{
Robert Carr9524cb32017-02-13 11:32:32 -08003374 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003375 status_t err = NO_ERROR;
3376 sp<Layer> l(client->getLayerUser(handle));
3377 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003378 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003379 err = removeLayer(l);
3380 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3381 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003382 }
3383 return err;
3384}
3385
Mathias Agopian13127d82013-03-05 17:47:11 -08003386status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003387{
Mathias Agopian67106042013-03-14 19:18:13 -07003388 // called by ~LayerCleaner() when all references to the IBinder (handle)
3389 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003390 sp<Layer> l = layer.promote();
3391 if (l == nullptr) {
3392 // The layer has already been removed, carry on
3393 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003394 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003395 // If we have a parent, then we can continue to live as long as it does.
3396 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003397}
3398
Mathias Agopianb60314a2012-04-10 22:09:54 -07003399// ---------------------------------------------------------------------------
3400
Andy McFadden13a082e2012-08-24 10:16:42 -07003401void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003402 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003403 Vector<ComposerState> state;
3404 Vector<DisplayState> displays;
3405 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003406 d.what = DisplayState::eDisplayProjectionChanged |
3407 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003408 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003409 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003410 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003411 d.frame.makeInvalid();
3412 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003413 d.width = 0;
3414 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003415 displays.add(d);
3416 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003417 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3418 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003419
Dan Stoza9e56aa02015-11-02 13:00:03 -08003420 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3421 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003422 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003423
Brian Andersond0010582017-03-07 13:20:31 -08003424 // Use phase of 0 since phase is not known.
3425 // Use latency of 0, which will snap to the ideal latency.
3426 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003427}
3428
3429void SurfaceFlinger::initializeDisplays() {
3430 class MessageScreenInitialized : public MessageBase {
3431 SurfaceFlinger* flinger;
3432 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003433 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003434 virtual bool handler() {
3435 flinger->onInitializeDisplays();
3436 return true;
3437 }
3438 };
3439 sp<MessageBase> msg = new MessageScreenInitialized(this);
3440 postMessageAsync(msg); // we may be called from main thread, use async message
3441}
3442
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003443void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003444 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003445 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3446 this);
3447 int32_t type = hw->getDisplayType();
3448 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003449
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003450 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003451 return;
3452 }
3453
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003454 hw->setPowerMode(mode);
3455 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3456 ALOGW("Trying to set power mode for virtual display");
3457 return;
3458 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003459
Irvelffc9efc2016-07-27 15:16:37 -07003460 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003461 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003462 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3463 if (idx < 0) {
3464 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3465 return;
3466 }
3467 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3468 }
3469
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003470 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003471 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003472 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003473 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3474 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003475 // FIXME: eventthread only knows about the main display right now
3476 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003477 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003478 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003479
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003480 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003481 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003482 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003483
3484 struct sched_param param = {0};
3485 param.sched_priority = 1;
3486 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3487 ALOGW("Couldn't set SCHED_FIFO on display on");
3488 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003489 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003490 // Turn off the display
3491 struct sched_param param = {0};
3492 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3493 ALOGW("Couldn't set SCHED_OTHER on display off");
3494 }
3495
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003496 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3497 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003498 disableHardwareVsync(true); // also cancels any in-progress resync
3499
Mathias Agopiancde87a32012-09-13 14:09:01 -07003500 // FIXME: eventthread only knows about the main display right now
3501 mEventThread->onScreenReleased();
3502 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003503
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003504 getHwComposer().setPowerMode(type, mode);
3505 mVisibleRegionsDirty = true;
3506 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003507 } else if (mode == HWC_POWER_MODE_DOZE ||
3508 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003509 // Update display while dozing
3510 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003511 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3512 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003513 // FIXME: eventthread only knows about the main display right now
3514 mEventThread->onScreenAcquired();
3515 resyncToHardwareVsync(true);
3516 }
3517 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3518 // Leave display going to doze
3519 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3520 disableHardwareVsync(true); // also cancels any in-progress resync
3521 // FIXME: eventthread only knows about the main display right now
3522 mEventThread->onScreenReleased();
3523 }
3524 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003525 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003526 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003527 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003528 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003529}
3530
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003531void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3532 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003533 SurfaceFlinger& mFlinger;
3534 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003535 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003536 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003537 MessageSetPowerMode(SurfaceFlinger& flinger,
3538 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3539 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003540 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003541 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003542 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003543 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003544 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003545 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003546 ALOGW("Attempt to set power mode = %d for virtual display",
3547 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003548 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003549 mFlinger.setPowerModeInternal(
3550 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003551 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003552 return true;
3553 }
3554 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003555 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003556 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003557}
3558
3559// ---------------------------------------------------------------------------
3560
Vishnu Nair6a408532017-10-24 09:11:27 -07003561status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003562 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003563
Mathias Agopianbd115332013-04-18 16:41:04 -07003564 IPCThreadState* ipc = IPCThreadState::self();
3565 const int pid = ipc->getCallingPid();
3566 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003567
Mathias Agopianbd115332013-04-18 16:41:04 -07003568 if ((uid != AID_SHELL) &&
3569 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003570 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003571 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003573 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003574 // (this would indicate SF is stuck, but we want to be able to
3575 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003576 status_t err = mStateLock.timedLock(s2ns(1));
3577 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003578 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003579 result.appendFormat(
3580 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3581 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003582 }
3583
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003584 bool dumpAll = true;
3585 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003586 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003587
3588 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003589 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003590 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3591 dumpAll = false;
3592 }
3593
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003594 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003595 if ((index < numArgs) &&
3596 (args[index] == String16("--list"))) {
3597 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003598 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003599 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003600 }
3601
3602 if ((index < numArgs) &&
3603 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003604 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003605 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003606 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003607 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003608
3609 if ((index < numArgs) &&
3610 (args[index] == String16("--latency-clear"))) {
3611 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003612 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003613 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003614 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003615
3616 if ((index < numArgs) &&
3617 (args[index] == String16("--dispsync"))) {
3618 index++;
3619 mPrimaryDispSync.dump(result);
3620 dumpAll = false;
3621 }
Dan Stozab90cf072015-03-05 11:05:59 -08003622
3623 if ((index < numArgs) &&
3624 (args[index] == String16("--static-screen"))) {
3625 index++;
3626 dumpStaticScreenStats(result);
3627 dumpAll = false;
3628 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003629
3630 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003631 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003632 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003633 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003634 dumpAll = false;
3635 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003636
3637 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3638 index++;
3639 dumpWideColorInfo(result);
3640 dumpAll = false;
3641 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003642 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003643
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003644 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003645 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003646 }
3647
Mathias Agopian9795c422009-08-26 16:36:26 -07003648 if (locked) {
3649 mStateLock.unlock();
3650 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003651 }
3652 write(fd, result.string(), result.size());
3653 return NO_ERROR;
3654}
3655
Dan Stozac7014012014-02-14 15:03:43 -08003656void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3657 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003658{
Robert Carr2047fae2016-11-28 14:09:09 -08003659 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003660 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003661 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003662}
3663
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003664void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003665 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003666{
3667 String8 name;
3668 if (index < args.size()) {
3669 name = String8(args[index]);
3670 index++;
3671 }
3672
Dan Stoza9e56aa02015-11-02 13:00:03 -08003673 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3674 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003675 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003676
3677 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003678 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003679 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003680 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003681 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003682 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003683 }
Robert Carr2047fae2016-11-28 14:09:09 -08003684 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003685 }
3686}
3687
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003688void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003689 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003690{
3691 String8 name;
3692 if (index < args.size()) {
3693 name = String8(args[index]);
3694 index++;
3695 }
3696
Robert Carr2047fae2016-11-28 14:09:09 -08003697 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003698 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003699 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003700 }
Robert Carr2047fae2016-11-28 14:09:09 -08003701 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003702
Svetoslavd85084b2014-03-20 10:28:31 -07003703 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003704}
3705
Jamie Gennis6547ff42013-07-16 20:12:42 -07003706// This should only be called from the main thread. Otherwise it would need
3707// the lock and should use mCurrentState rather than mDrawingState.
3708void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003709 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003710 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003711 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003712
3713 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3714}
3715
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003716void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003717{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003718 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003719 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3720
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003721 if (isLayerTripleBufferingDisabled())
3722 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003723
3724 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003725 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003726 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003727 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003728 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3729 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003730 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003731}
3732
Dan Stozab90cf072015-03-05 11:05:59 -08003733void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3734{
3735 result.appendFormat("Static screen stats:\n");
3736 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3737 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3738 float percent = 100.0f *
3739 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3740 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3741 b + 1, bucketTimeSec, percent);
3742 }
3743 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3744 float percent = 100.0f *
3745 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3746 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3747 NUM_BUCKETS - 1, bucketTimeSec, percent);
3748}
3749
Dan Stozae77c7662016-05-13 11:37:28 -07003750void SurfaceFlinger::recordBufferingStats(const char* layerName,
3751 std::vector<OccupancyTracker::Segment>&& history) {
3752 Mutex::Autolock lock(mBufferingStatsMutex);
3753 auto& stats = mBufferingStats[layerName];
3754 for (const auto& segment : history) {
3755 if (!segment.usedThirdBuffer) {
3756 stats.twoBufferTime += segment.totalTime;
3757 }
3758 if (segment.occupancyAverage < 1.0f) {
3759 stats.doubleBufferedTime += segment.totalTime;
3760 } else if (segment.occupancyAverage < 2.0f) {
3761 stats.tripleBufferedTime += segment.totalTime;
3762 }
3763 ++stats.numSegments;
3764 stats.totalTime += segment.totalTime;
3765 }
3766}
3767
Brian Andersond6927fb2016-07-23 23:37:30 -07003768void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3769 result.appendFormat("Layer frame timestamps:\n");
3770
3771 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3772 const size_t count = currentLayers.size();
3773 for (size_t i=0 ; i<count ; i++) {
3774 currentLayers[i]->dumpFrameEvents(result);
3775 }
3776}
3777
Dan Stozae77c7662016-05-13 11:37:28 -07003778void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3779 result.append("Buffering stats:\n");
3780 result.append(" [Layer name] <Active time> <Two buffer> "
3781 "<Double buffered> <Triple buffered>\n");
3782 Mutex::Autolock lock(mBufferingStatsMutex);
3783 typedef std::tuple<std::string, float, float, float> BufferTuple;
3784 std::map<float, BufferTuple, std::greater<float>> sorted;
3785 for (const auto& statsPair : mBufferingStats) {
3786 const char* name = statsPair.first.c_str();
3787 const BufferingStats& stats = statsPair.second;
3788 if (stats.numSegments == 0) {
3789 continue;
3790 }
3791 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3792 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3793 stats.totalTime;
3794 float doubleBufferRatio = static_cast<float>(
3795 stats.doubleBufferedTime) / stats.totalTime;
3796 float tripleBufferRatio = static_cast<float>(
3797 stats.tripleBufferedTime) / stats.totalTime;
3798 sorted.insert({activeTime, {name, twoBufferRatio,
3799 doubleBufferRatio, tripleBufferRatio}});
3800 }
3801 for (const auto& sortedPair : sorted) {
3802 float activeTime = sortedPair.first;
3803 const BufferTuple& values = sortedPair.second;
3804 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3805 std::get<0>(values).c_str(), activeTime,
3806 std::get<1>(values), std::get<2>(values),
3807 std::get<3>(values));
3808 }
3809 result.append("\n");
3810}
3811
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003812void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3813 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003814 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003815
3816 // TODO: print out if wide-color mode is active or not
3817
3818 for (size_t d = 0; d < mDisplays.size(); d++) {
3819 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3820 int32_t hwcId = displayDevice->getHwcDisplayId();
3821 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3822 continue;
3823 }
3824
3825 result.appendFormat("Display %d color modes:\n", hwcId);
3826 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3827 for (auto&& mode : modes) {
3828 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3829 }
3830
3831 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3832 result.appendFormat(" Current color mode: %s (%d)\n",
3833 decodeColorMode(currentMode).c_str(), currentMode);
3834 }
3835 result.append("\n");
3836}
3837
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003838LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003839 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003840 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3841 const State& state = useDrawing ? mDrawingState : mCurrentState;
3842 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003843 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003844 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003845 });
3846
3847 return layersProto;
3848}
3849
Mathias Agopian74d211a2013-04-22 16:55:35 +02003850void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3851 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003852{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003853 bool colorize = false;
3854 if (index < args.size()
3855 && (args[index] == String16("--color"))) {
3856 colorize = true;
3857 index++;
3858 }
3859
3860 Colorizer colorizer(colorize);
3861
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003862 // figure out if we're stuck somewhere
3863 const nsecs_t now = systemTime();
3864 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3865 const nsecs_t inTransaction(mDebugInTransaction);
3866 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3867 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3868
3869 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003870 * Dump library configuration.
3871 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003872
3873 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003874 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003875 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003876 appendSfConfigString(result);
3877 appendUiConfigString(result);
3878 appendGuiConfigString(result);
3879 result.append("\n");
3880
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003881 result.append("\nWide-Color information:\n");
3882 dumpWideColorInfo(result);
3883
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003884 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003885 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003886 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003887 result.append(SyncFeatures::getInstance().toString());
3888 result.append("\n");
3889
Dan Stoza9e56aa02015-11-02 13:00:03 -08003890 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3891
Andy McFadden41d67d72014-04-25 16:58:34 -07003892 colorizer.bold(result);
3893 result.append("DispSync configuration: ");
3894 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003895 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003896 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003897 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003898 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003899 result.append("\n");
3900
Dan Stozab90cf072015-03-05 11:05:59 -08003901 // Dump static screen stats
3902 result.append("\n");
3903 dumpStaticScreenStats(result);
3904 result.append("\n");
3905
Dan Stozae77c7662016-05-13 11:37:28 -07003906 dumpBufferingStats(result);
3907
Andy McFadden4803b742012-09-24 19:07:20 -07003908 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003909 * Dump the visible layer list
3910 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003911 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003912 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003913 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003914
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003915 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003916 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3917 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003918
3919 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003920 * Dump Display state
3921 */
3922
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003923 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003924 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003925 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003926 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3927 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003928 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003929 }
3930
3931 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003932 * Dump SurfaceFlinger global state
3933 */
3934
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003935 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003936 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003937 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003938
Mathias Agopian888c8222012-08-04 21:10:38 -07003939 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003940 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003941
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003942 colorizer.bold(result);
3943 result.appendFormat("EGL implementation : %s\n",
3944 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3945 colorizer.reset(result);
3946 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003947 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003948
Mathias Agopian875d8e12013-06-07 15:35:48 -07003949 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003950
Mathias Agopian42977342012-08-05 00:40:46 -07003951 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003952 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3953 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003954 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003955 " last eglSwapBuffers() time: %f us\n"
3956 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003957 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003958 " refresh-rate : %f fps\n"
3959 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003960 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003961 " gpu_to_cpu_unsupported : %d\n"
3962 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003963 mLastSwapBufferTime/1000.0,
3964 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003965 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003966 1e9 / activeConfig->getVsyncPeriod(),
3967 activeConfig->getDpiX(),
3968 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003969 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003970
Mathias Agopian74d211a2013-04-22 16:55:35 +02003971 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003972 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003973
Mathias Agopian74d211a2013-04-22 16:55:35 +02003974 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003975 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003976
3977 /*
3978 * VSYNC state
3979 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003980 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003981 result.append("\n");
3982
3983 /*
3984 * HWC layer minidump
3985 */
3986 for (size_t d = 0; d < mDisplays.size(); d++) {
3987 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3988 int32_t hwcId = displayDevice->getHwcDisplayId();
3989 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3990 continue;
3991 }
3992
3993 result.appendFormat("Display %d HWC layers:\n", hwcId);
3994 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003995 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003996 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003997 });
Dan Stozae22aec72016-08-01 13:20:59 -07003998 result.append("\n");
3999 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004000
4001 /*
4002 * Dump HWComposer state
4003 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004004 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004005 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004006 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004007 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004008 result.appendFormat(" h/w composer %s\n",
4009 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004010 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004011
4012 /*
4013 * Dump gralloc state
4014 */
4015 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4016 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004017
4018 /*
4019 * Dump VrFlinger state if in use.
4020 */
4021 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4022 result.append("VrFlinger state:\n");
4023 result.append(mVrFlinger->Dump().c_str());
4024 result.append("\n");
4025 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004026}
4027
Mathias Agopian13127d82013-03-05 17:47:11 -08004028const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004029SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004030 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004031 wp<IBinder> dpy;
4032 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4033 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4034 dpy = mDisplays.keyAt(i);
4035 break;
4036 }
4037 }
4038 if (dpy == NULL) {
4039 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4040 // Just use the primary display so we have something to return
4041 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4042 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004043 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004044}
4045
Keun young Park63f165f2012-08-31 10:53:36 -07004046bool SurfaceFlinger::startDdmConnection()
4047{
4048 void* libddmconnection_dso =
4049 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4050 if (!libddmconnection_dso) {
4051 return false;
4052 }
4053 void (*DdmConnection_start)(const char* name);
4054 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004055 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004056 if (!DdmConnection_start) {
4057 dlclose(libddmconnection_dso);
4058 return false;
4059 }
4060 (*DdmConnection_start)(getServiceName());
4061 return true;
4062}
4063
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004064status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004065 switch (code) {
4066 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004067 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004068 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004069 case CLEAR_ANIMATION_FRAME_STATS:
4070 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004071 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004072 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004073 case ENABLE_VSYNC_INJECTIONS:
4074 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004075 {
4076 // codes that require permission check
4077 IPCThreadState* ipc = IPCThreadState::self();
4078 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004079 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004080 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004081 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004082 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004083 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004084 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004085 break;
4086 }
Robert Carr1db73f62016-12-21 12:58:51 -08004087 /*
4088 * Calling setTransactionState is safe, because you need to have been
4089 * granted a reference to Client* and Handle* to do anything with it.
4090 *
4091 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4092 */
4093 case SET_TRANSACTION_STATE:
4094 case CREATE_SCOPED_CONNECTION:
4095 {
4096 return OK;
4097 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004098 case CAPTURE_SCREEN:
4099 {
4100 // codes that require permission check
4101 IPCThreadState* ipc = IPCThreadState::self();
4102 const int pid = ipc->getCallingPid();
4103 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004104 if ((uid != AID_GRAPHICS) &&
4105 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004106 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004107 return PERMISSION_DENIED;
4108 }
4109 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004110 }
chaviwa76b2712017-09-20 12:02:26 -07004111 case CAPTURE_LAYERS: {
4112 IPCThreadState* ipc = IPCThreadState::self();
4113 const int pid = ipc->getCallingPid();
4114 const int uid = ipc->getCallingUid();
4115 if ((uid != AID_GRAPHICS) &&
4116 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4117 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4118 return PERMISSION_DENIED;
4119 }
4120 break;
4121 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004122 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004123 return OK;
4124}
4125
4126status_t SurfaceFlinger::onTransact(
4127 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4128{
4129 status_t credentialCheck = CheckTransactCodeCredentials(code);
4130 if (credentialCheck != OK) {
4131 return credentialCheck;
4132 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004134 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4135 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004136 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004137 IPCThreadState* ipc = IPCThreadState::self();
4138 const int uid = ipc->getCallingUid();
4139 if (CC_UNLIKELY(uid != AID_SYSTEM
4140 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004141 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004142 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004143 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004144 return PERMISSION_DENIED;
4145 }
4146 int n;
4147 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004148 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004149 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004150 return NO_ERROR;
4151 case 1002: // SHOW_UPDATES
4152 n = data.readInt32();
4153 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004154 invalidateHwcGeometry();
4155 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004156 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004157 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004158 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004159 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004160 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004161 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004162 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004163 setTransactionFlags(
4164 eTransactionNeeded|
4165 eDisplayTransactionNeeded|
4166 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004167 return NO_ERROR;
4168 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004169 case 1006:{ // send empty update
4170 signalRefresh();
4171 return NO_ERROR;
4172 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004173 case 1008: // toggle use of hw composer
4174 n = data.readInt32();
4175 mDebugDisableHWC = n ? 1 : 0;
4176 invalidateHwcGeometry();
4177 repaintEverything();
4178 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004179 case 1009: // toggle use of transform hint
4180 n = data.readInt32();
4181 mDebugDisableTransformHint = n ? 1 : 0;
4182 invalidateHwcGeometry();
4183 repaintEverything();
4184 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004185 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004186 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004187 reply->writeInt32(0);
4188 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004189 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004190 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004191 return NO_ERROR;
4192 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004193 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004194 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004195 return NO_ERROR;
4196 }
4197 case 1014: {
4198 // daltonize
4199 n = data.readInt32();
4200 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004201 case 1:
4202 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4203 break;
4204 case 2:
4205 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4206 break;
4207 case 3:
4208 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4209 break;
4210 default:
4211 mDaltonizer.setType(ColorBlindnessType::None);
4212 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004213 }
4214 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004215 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004216 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004217 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004218 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004219 invalidateHwcGeometry();
4220 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004221 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004222 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004223 case 1015: {
4224 // apply a color matrix
4225 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004226 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004227 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004228 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004229 for (size_t j = 0; j < 4; j++) {
4230 mColorMatrix[i][j] = data.readFloat();
4231 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004232 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004233 } else {
4234 mColorMatrix = mat4();
4235 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004236
4237 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4238 // the division by w in the fragment shader
4239 float4 lastRow(transpose(mColorMatrix)[3]);
4240 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4241 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4242 }
4243
Alan Viverette9c5a3332013-09-12 20:04:35 -07004244 invalidateHwcGeometry();
4245 repaintEverything();
4246 return NO_ERROR;
4247 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004248 // This is an experimental interface
4249 // Needs to be shifted to proper binder interface when we productize
4250 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004251 n = data.readInt32();
4252 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004253 return NO_ERROR;
4254 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004255 case 1017: {
4256 n = data.readInt32();
4257 mForceFullDamage = static_cast<bool>(n);
4258 return NO_ERROR;
4259 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004260 case 1018: { // Modify Choreographer's phase offset
4261 n = data.readInt32();
4262 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4263 return NO_ERROR;
4264 }
4265 case 1019: { // Modify SurfaceFlinger's phase offset
4266 n = data.readInt32();
4267 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4268 return NO_ERROR;
4269 }
Irvel468051e2016-06-13 16:44:44 -07004270 case 1020: { // Layer updates interceptor
4271 n = data.readInt32();
4272 if (n) {
4273 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004274 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004275 }
4276 else{
4277 ALOGV("Interceptor disabled");
4278 mInterceptor.disable();
4279 }
4280 return NO_ERROR;
4281 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004282 case 1021: { // Disable HWC virtual displays
4283 n = data.readInt32();
4284 mUseHwcVirtualDisplays = !n;
4285 return NO_ERROR;
4286 }
Romain Guy0147a172017-06-01 13:53:56 -07004287 case 1022: { // Set saturation boost
4288 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4289
4290 invalidateHwcGeometry();
4291 repaintEverything();
4292 return NO_ERROR;
4293 }
Romain Guy54f154a2017-10-24 21:40:32 +01004294 case 1023: { // Set native mode
4295 mForceNativeColorMode = data.readInt32() == 1;
4296
4297 invalidateHwcGeometry();
4298 repaintEverything();
4299 return NO_ERROR;
4300 }
4301 case 1024: { // Is wide color gamut rendering/color management supported?
4302 reply->writeBool(hasWideColorDisplay);
4303 return NO_ERROR;
4304 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004305 case 1025: { // tracing
4306 n = data.readInt32();
4307 if (n) {
4308 ALOGV("LayerTracing enabled");
4309 mTracing.enable();
4310 doTracing("tracing.enable");
4311 reply->writeInt32(NO_ERROR);
4312 } else {
4313 ALOGV("LayerTracing disabled");
4314 status_t err = mTracing.disable();
4315 reply->writeInt32(err);
4316 }
4317 return NO_ERROR;
4318 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004319 }
4320 }
4321 return err;
4322}
4323
Steven Thomas6d8110b2017-08-31 18:24:21 -07004324void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004325 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004326 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004327}
4328
Steven Thomas6d8110b2017-08-31 18:24:21 -07004329void SurfaceFlinger::repaintEverything() {
4330 ConditionalLock _l(mStateLock,
4331 std::this_thread::get_id() != mMainThreadId);
4332 repaintEverythingLocked();
4333}
4334
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004335// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4336class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004337public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004338 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4339 ~WindowDisconnector() {
4340 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004341 }
4342
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004343private:
4344 ANativeWindow* mWindow;
4345 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004346};
4347
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004348static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4349 uint32_t requestedHeight, bool hasWideColorDisplay,
4350 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4351 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4352 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4353
4354 int err = 0;
4355 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4356 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4357 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4358 err |= native_window_set_usage(window, usage);
4359
4360 if (hasWideColorDisplay) {
4361 err |= native_window_set_buffers_data_space(window,
4362 renderEngineUsesWideColor
4363 ? HAL_DATASPACE_DISPLAY_P3
4364 : HAL_DATASPACE_V0_SRGB);
4365 }
4366
4367 if (err != NO_ERROR) {
4368 return BAD_VALUE;
4369 }
4370
4371 /* TODO: Once we have the sync framework everywhere this can use
4372 * server-side waits on the fence that dequeueBuffer returns.
4373 */
4374 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4375 if (err != NO_ERROR) {
4376 return err;
4377 }
4378
4379 return NO_ERROR;
4380}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004381
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004382status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
chaviwa76b2712017-09-20 12:02:26 -07004383 const sp<IGraphicBufferProducer>& producer, Rect sourceCrop,
4384 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4385 int32_t maxLayerZ, bool useIdentityTransform,
4386 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004387 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004388
chaviwa76b2712017-09-20 12:02:26 -07004389 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4390
4391 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4392 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4393
4394 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4395 device, minLayerZ, maxLayerZ, std::placeholders::_1);
4396 return captureScreenCommon(renderArea, traverseLayers, producer, useIdentityTransform);
4397}
4398
4399status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
4400 const sp<IGraphicBufferProducer>& producer,
chaviw7206d492017-11-10 16:16:12 -08004401 const Rect& sourceCrop, float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004402 ATRACE_CALL();
4403
4404 class LayerRenderArea : public RenderArea {
4405 public:
chaviw7206d492017-11-10 16:16:12 -08004406 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
4407 int32_t reqHeight)
4408 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004409 const Transform& getTransform() const override {
4410 // Make the top level transform the inverse the transform and it's parent so it sets
4411 // the whole capture back to 0,0
4412 return *new Transform(mLayer->getTransform().inverse());
4413 }
4414 Rect getBounds() const override {
4415 const Layer::State& layerState(mLayer->getDrawingState());
4416 return Rect(layerState.active.w, layerState.active.h);
4417 }
4418 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4419 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4420 bool isSecure() const override { return false; }
4421 bool needsFiltering() const override { return false; }
4422
chaviw7206d492017-11-10 16:16:12 -08004423 Rect getSourceCrop() const override {
4424 if (mCrop.isEmpty()) {
4425 return getBounds();
4426 } else {
4427 return mCrop;
4428 }
4429 }
chaviwa76b2712017-09-20 12:02:26 -07004430 bool getWideColorSupport() const override { return false; }
4431 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4432
4433 private:
chaviw7206d492017-11-10 16:16:12 -08004434 const sp<Layer> mLayer;
4435 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004436 };
4437
4438 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4439 auto parent = layerHandle->owner.promote();
4440
chaviw7206d492017-11-10 16:16:12 -08004441 if (parent == nullptr || parent->isPendingRemoval()) {
4442 ALOGE("captureLayers called with a removed parent");
4443 return NAME_NOT_FOUND;
4444 }
4445
4446 Rect crop(sourceCrop);
4447 if (sourceCrop.width() <= 0) {
4448 crop.left = 0;
4449 crop.right = parent->getCurrentState().active.w;
4450 }
4451
4452 if (sourceCrop.height() <= 0) {
4453 crop.top = 0;
4454 crop.bottom = parent->getCurrentState().active.h;
4455 }
4456
4457 int32_t reqWidth = crop.width() * frameScale;
4458 int32_t reqHeight = crop.height() * frameScale;
4459
4460 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4461
chaviwa76b2712017-09-20 12:02:26 -07004462 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4463 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4464 if (!layer->isVisible()) {
4465 return;
4466 }
4467 visitor(layer);
4468 });
4469 };
4470 return captureScreenCommon(renderArea, traverseLayers, producer, false);
4471}
4472
4473status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4474 TraverseLayersFunction traverseLayers,
4475 const sp<IGraphicBufferProducer>& producer,
4476 bool useIdentityTransform) {
4477 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004478
4479 if (CC_UNLIKELY(producer == 0))
4480 return BAD_VALUE;
4481
chaviwa76b2712017-09-20 12:02:26 -07004482 renderArea.updateDimensions();
4483
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004484 // if we have secure windows on this display, never allow the screen capture
4485 // unless the producer interface is local (i.e.: we can take a screenshot for
4486 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004487 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004488
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004489 // create a surface (because we're a producer, and we need to
4490 // dequeue/queue a buffer)
4491 sp<Surface> surface = new Surface(producer, false);
4492
4493 // Put the screenshot Surface into async mode so that
4494 // Layer::headFenceHasSignaled will always return true and we'll latch the
4495 // first buffer regardless of whether or not its acquire fence has
4496 // signaled. This is needed to avoid a race condition in the rotation
4497 // animation. See b/30209608
4498 surface->setAsyncMode(true);
4499
4500 ANativeWindow* window = surface.get();
4501
4502 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4503 if (result != NO_ERROR) {
4504 return result;
4505 }
4506 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4507
4508 ANativeWindowBuffer* buffer = nullptr;
chaviwa76b2712017-09-20 12:02:26 -07004509 result = getWindowBuffer(window, renderArea.getReqWidth(), renderArea.getReqHeight(),
4510 hasWideColorDisplay && !mForceNativeColorMode,
4511 getRenderEngine().usesWideColor(), &buffer);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004512 if (result != NO_ERROR) {
4513 return result;
4514 }
4515
4516 // This mutex protects syncFd and captureResult for communication of the return values from the
4517 // main thread back to this Binder thread
4518 std::mutex captureMutex;
4519 std::condition_variable captureCondition;
4520 std::unique_lock<std::mutex> captureLock(captureMutex);
4521 int syncFd = -1;
4522 std::optional<status_t> captureResult;
4523
4524 sp<LambdaMessage> message = new LambdaMessage([&]() {
4525 // If there is a refresh pending, bug out early and tell the binder thread to try again
4526 // after the refresh.
4527 if (mRefreshPending) {
4528 ATRACE_NAME("Skipping screenshot for now");
4529 std::unique_lock<std::mutex> captureLock(captureMutex);
4530 captureResult = std::make_optional<status_t>(EAGAIN);
4531 captureCondition.notify_one();
4532 return;
4533 }
4534
4535 status_t result = NO_ERROR;
4536 int fd = -1;
4537 {
4538 Mutex::Autolock _l(mStateLock);
chaviwa76b2712017-09-20 12:02:26 -07004539 result = captureScreenImplLocked(renderArea, traverseLayers, buffer,
4540 useIdentityTransform, isLocalScreenshot, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004541 }
4542
4543 {
4544 std::unique_lock<std::mutex> captureLock(captureMutex);
4545 syncFd = fd;
4546 captureResult = std::make_optional<status_t>(result);
4547 captureCondition.notify_one();
4548 }
4549 });
4550
4551 result = postMessageAsync(message);
4552 if (result == NO_ERROR) {
4553 captureCondition.wait(captureLock, [&]() { return captureResult; });
4554 while (*captureResult == EAGAIN) {
4555 captureResult.reset();
4556 result = postMessageAsync(message);
4557 if (result != NO_ERROR) {
4558 return result;
4559 }
4560 captureCondition.wait(captureLock, [&]() { return captureResult; });
4561 }
4562 result = *captureResult;
4563 }
4564
4565 if (result == NO_ERROR) {
4566 // queueBuffer takes ownership of syncFd
4567 result = window->queueBuffer(window, buffer, syncFd);
4568 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004569 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004570}
4571
chaviwa76b2712017-09-20 12:02:26 -07004572void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4573 TraverseLayersFunction traverseLayers, bool yswap,
4574 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004575 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004576
Mathias Agopian3f844832013-08-07 21:24:32 -07004577 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004578
4579 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004580 const auto raWidth = renderArea.getWidth();
4581 const auto raHeight = renderArea.getHeight();
4582
4583 const auto reqWidth = renderArea.getReqWidth();
4584 const auto reqHeight = renderArea.getReqHeight();
4585 Rect sourceCrop = renderArea.getSourceCrop();
4586
4587 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4588 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004589
Dan Stozac1879002014-05-22 15:59:05 -07004590 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004591 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004592 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004593 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004594 }
4595
4596 // ensure that sourceCrop is inside screen
4597 if (sourceCrop.left < 0) {
4598 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4599 }
chaviwa76b2712017-09-20 12:02:26 -07004600 if (sourceCrop.right > raWidth) {
4601 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004602 }
4603 if (sourceCrop.top < 0) {
4604 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4605 }
chaviwa76b2712017-09-20 12:02:26 -07004606 if (sourceCrop.bottom > raHeight) {
4607 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004608 }
4609
chaviwa76b2712017-09-20 12:02:26 -07004610 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
4611 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004612
Mathias Agopian180f10d2013-04-10 22:55:41 -07004613 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004614 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004615
4616 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004617 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4618 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004619 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004620
4621 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004622 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004623
chaviwa76b2712017-09-20 12:02:26 -07004624 traverseLayers([&](Layer* layer) {
4625 if (filtering) layer->setFiltering(true);
4626 layer->draw(renderArea, useIdentityTransform);
4627 if (filtering) layer->setFiltering(false);
4628 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004629}
4630
Dan Stozaabcda352017-06-01 14:37:39 -07004631// A simple RAII class that holds an EGLImage and destroys it either:
4632// a) When the destroy() method is called
4633// b) When the object goes out of scope
4634class ImageHolder {
4635public:
4636 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4637 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004638
Dan Stozaabcda352017-06-01 14:37:39 -07004639 void destroy() {
4640 if (mImage != EGL_NO_IMAGE_KHR) {
4641 eglDestroyImageKHR(mDisplay, mImage);
4642 mImage = EGL_NO_IMAGE_KHR;
4643 }
4644 }
4645
4646private:
4647 const EGLDisplay mDisplay;
4648 EGLImageKHR mImage;
4649};
4650
chaviwa76b2712017-09-20 12:02:26 -07004651status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4652 TraverseLayersFunction traverseLayers,
4653 ANativeWindowBuffer* buffer,
4654 bool useIdentityTransform, bool isLocalScreenshot,
4655 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004656 ATRACE_CALL();
4657
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004658 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004659
4660 traverseLayers([&](Layer* layer) {
4661 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4662 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004663
4664 if (!isLocalScreenshot && secureLayerIsVisible) {
4665 ALOGW("FB is protected: PERMISSION_DENIED");
4666 return PERMISSION_DENIED;
4667 }
4668
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004669 int syncFd = -1;
4670 // create an EGLImage from the buffer so we can later
4671 // turn it into a texture
4672 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4673 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4674 if (image == EGL_NO_IMAGE_KHR) {
4675 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004676 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004677
Dan Stozaabcda352017-06-01 14:37:39 -07004678 // This will automatically destroy the image if we return before calling its destroy method
4679 ImageHolder imageHolder(mEGLDisplay, image);
4680
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004681 // this binds the given EGLImage as a framebuffer for the
4682 // duration of this scope.
4683 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004684 if (imageBond.getStatus() != NO_ERROR) {
4685 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004686 return INVALID_OPERATION;
4687 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004688
Dan Stozaabcda352017-06-01 14:37:39 -07004689 // this will in fact render into our dequeued buffer
4690 // via an FBO, which means we didn't have to create
4691 // an EGLSurface and therefore we're not
4692 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004693 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004694
Dan Stozaabcda352017-06-01 14:37:39 -07004695 // Attempt to create a sync khr object that can produce a sync point. If that
4696 // isn't available, create a non-dupable sync object in the fallback path and
4697 // wait on it directly.
4698 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4699 if (!DEBUG_SCREENSHOTS) {
4700 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4701 // native fence fd will not be populated until flush() is done.
4702 getRenderEngine().flush();
4703 }
4704
4705 if (sync != EGL_NO_SYNC_KHR) {
4706 // get the sync fd
4707 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4708 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4709 ALOGW("captureScreen: failed to dup sync khr object");
4710 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004711 }
Dan Stozaabcda352017-06-01 14:37:39 -07004712 eglDestroySyncKHR(mEGLDisplay, sync);
4713 } else {
4714 // fallback path
4715 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004716 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004717 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4718 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4719 EGLint eglErr = eglGetError();
4720 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4721 ALOGW("captureScreen: fence wait timed out");
4722 } else {
4723 ALOGW_IF(eglErr != EGL_SUCCESS,
4724 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004725 }
4726 eglDestroySyncKHR(mEGLDisplay, sync);
4727 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004728 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004729 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004730 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004731 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004732
4733 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004734 const auto reqWidth = renderArea.getReqWidth();
4735 const auto reqHeight = renderArea.getReqHeight();
4736
Dan Stozaabcda352017-06-01 14:37:39 -07004737 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4738 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004739 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004740 delete [] pixels;
4741 }
4742
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004743 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004744 imageHolder.destroy();
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004745 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004746}
4747
Mathias Agopiand5556842013-09-19 17:08:37 -07004748void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004749 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004750 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004751 for (size_t y = 0; y < h; y++) {
4752 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4753 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004754 if (p[x] != 0xFF000000) return;
4755 }
4756 }
chaviwa76b2712017-09-20 12:02:26 -07004757 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004758
Robert Carr2047fae2016-11-28 14:09:09 -08004759 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004760 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004761 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004762 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4763 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4764 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4765 static_cast<float>(state.color.a));
4766 i++;
4767 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004768 }
4769}
4770
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004771// ---------------------------------------------------------------------------
4772
Dan Stoza412903f2017-04-27 13:42:17 -07004773void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4774 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004775}
4776
Dan Stoza412903f2017-04-27 13:42:17 -07004777void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4778 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004779}
4780
chaviwa76b2712017-09-20 12:02:26 -07004781void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4782 int32_t maxLayerZ,
4783 const LayerVector::Visitor& visitor) {
4784 // We loop through the first level of layers without traversing,
4785 // as we need to interpret min/max layer Z in the top level Z space.
4786 for (const auto& layer : mDrawingState.layersSortedByZ) {
4787 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4788 continue;
4789 }
4790 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004791 // relative layers are traversed in Layer::traverseInZOrder
4792 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004793 continue;
4794 }
4795 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4796 if (!layer->isVisible()) {
4797 return;
4798 }
4799 visitor(layer);
4800 });
4801 }
4802}
4803
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004804}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004805
4806
4807#if defined(__gl_h_)
4808#error "don't include gl/gl.h in this file"
4809#endif
4810
4811#if defined(__gl2_h_)
4812#error "don't include gl2/gl2.h in this file"
4813#endif