blob: f3d3866a6563490e6299d18f12804fc5225d9b03 [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{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288}
289
Dan Stozac7014012014-02-14 15:03:43 -0800290void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800291{
292 // the window manager died on us. prepare its eulogy.
293
Andy McFadden13a082e2012-08-24 10:16:42 -0700294 // restore initial conditions (default device unblank, etc)
295 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800296
297 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700298 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800299}
300
Robert Carr1db73f62016-12-21 12:58:51 -0800301static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700302 status_t err = client->initCheck();
303 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800304 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 }
Robert Carr1db73f62016-12-21 12:58:51 -0800306 return nullptr;
307}
308
309sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
310 return initClient(new Client(this));
311}
312
313sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
314 const sp<IGraphicBufferProducer>& gbp) {
315 if (authenticateSurfaceTexture(gbp) == false) {
316 return nullptr;
317 }
318 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
319 if (layer == nullptr) {
320 return nullptr;
321 }
322
323 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324}
325
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700326sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
327 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700328{
329 class DisplayToken : public BBinder {
330 sp<SurfaceFlinger> flinger;
331 virtual ~DisplayToken() {
332 // no more references, this display must be terminated
333 Mutex::Autolock _l(flinger->mStateLock);
334 flinger->mCurrentState.displays.removeItem(this);
335 flinger->setTransactionFlags(eDisplayTransactionNeeded);
336 }
337 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700338 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700339 : flinger(flinger) {
340 }
341 };
342
343 sp<BBinder> token = new DisplayToken(this);
344
345 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700346 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700347 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700348 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700349 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700350 return token;
351}
352
Jesse Hall6c913be2013-08-08 12:15:49 -0700353void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
354 Mutex::Autolock _l(mStateLock);
355
356 ssize_t idx = mCurrentState.displays.indexOfKey(display);
357 if (idx < 0) {
358 ALOGW("destroyDisplay: invalid display token");
359 return;
360 }
361
362 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
363 if (!info.isVirtualDisplay()) {
364 ALOGE("destroyDisplay called for non-virtual display");
365 return;
366 }
Irvelffc9efc2016-07-27 15:16:37 -0700367 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700368 mCurrentState.displays.removeItemsAt(idx);
369 setTransactionFlags(eDisplayTransactionNeeded);
370}
371
Jesse Hall692c7232012-11-08 15:41:56 -0800372void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800373 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800374 ALOGW_IF(mBuiltinDisplays[type],
375 "Overwriting display token for display type %d", type);
376 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800377 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700378 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800379 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700380 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800381}
382
Mathias Agopiane57f2922012-08-09 16:29:12 -0700383sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700384 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700385 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
386 return NULL;
387 }
Jesse Hall692c7232012-11-08 15:41:56 -0800388 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700389}
390
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800391void SurfaceFlinger::bootFinished()
392{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700393 if (mStartPropertySetThread->join() != NO_ERROR) {
394 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800395 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396 const nsecs_t now = systemTime();
397 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000398 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700399
400 // wait patiently for the window manager death
401 const String16 name("window");
402 sp<IBinder> window(defaultServiceManager()->getService(name));
403 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700404 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700405 }
406
Steven Thomas050b2c82017-03-06 11:45:16 -0800407 if (mVrFlinger) {
408 mVrFlinger->OnBootFinished();
409 }
410
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700411 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700412 // formerly we would just kill the process, but we now ask it to exit so it
413 // can choose where to stop the animation.
414 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700415
416 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
417 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
418 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700419
Thierry Strudel2924d012017-08-14 15:19:37 -0700420 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700421 readPersistentProperties();
422 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700423 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Mathias Agopian3f844832013-08-07 21:24:32 -0700426void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700427 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700428 RenderEngine& engine;
429 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700430 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700431 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
432 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700433 }
434 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700435 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700436 return true;
437 }
438 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700439 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700440}
441
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442class DispSyncSource : public VSyncSource, private DispSync::Callback {
443public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700444 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000445 const char* name) :
446 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700447 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700448 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000449 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
450 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700451 mDispSync(dispSync),
452 mCallbackMutex(),
453 mCallback(),
454 mVsyncMutex(),
455 mPhaseOffset(phaseOffset),
456 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700457
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 virtual ~DispSyncSource() {}
459
460 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700461 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000463 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700464 static_cast<DispSync::Callback*>(this));
465 if (err != NO_ERROR) {
466 ALOGE("error registering vsync callback: %s (%d)",
467 strerror(-err), err);
468 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700469 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470 } else {
471 status_t err = mDispSync->removeEventListener(
472 static_cast<DispSync::Callback*>(this));
473 if (err != NO_ERROR) {
474 ALOGE("error unregistering vsync callback: %s (%d)",
475 strerror(-err), err);
476 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700477 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700478 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700479 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 }
481
482 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700483 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700484 mCallback = callback;
485 }
486
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700487 virtual void setPhaseOffset(nsecs_t phaseOffset) {
488 Mutex::Autolock lock(mVsyncMutex);
489
490 // Normalize phaseOffset to [0, period)
491 auto period = mDispSync->getPeriod();
492 phaseOffset %= period;
493 if (phaseOffset < 0) {
494 // If we're here, then phaseOffset is in (-period, 0). After this
495 // operation, it will be in (0, period)
496 phaseOffset += period;
497 }
498 mPhaseOffset = phaseOffset;
499
500 // If we're not enabled, we don't need to mess with the listeners
501 if (!mEnabled) {
502 return;
503 }
504
505 // Remove the listener with the old offset
506 status_t err = mDispSync->removeEventListener(
507 static_cast<DispSync::Callback*>(this));
508 if (err != NO_ERROR) {
509 ALOGE("error unregistering vsync callback: %s (%d)",
510 strerror(-err), err);
511 }
512
513 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000514 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700515 static_cast<DispSync::Callback*>(this));
516 if (err != NO_ERROR) {
517 ALOGE("error registering vsync callback: %s (%d)",
518 strerror(-err), err);
519 }
520 }
521
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522private:
523 virtual void onDispSyncEvent(nsecs_t when) {
524 sp<VSyncSource::Callback> callback;
525 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700526 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527 callback = mCallback;
528
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700529 if (mTraceVsync) {
530 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700531 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700532 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533 }
534
535 if (callback != NULL) {
536 callback->onVSyncEvent(when);
537 }
538 }
539
Tim Murray4a4e4a22016-04-19 16:29:23 +0000540 const char* const mName;
541
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 int mValue;
543
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700544 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700545 const String8 mVsyncOnLabel;
546 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700547
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700548 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700549
550 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700551 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700552
553 Mutex mVsyncMutex; // Protects the following
554 nsecs_t mPhaseOffset;
555 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700556};
557
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700558class InjectVSyncSource : public VSyncSource {
559public:
560 InjectVSyncSource() {}
561
562 virtual ~InjectVSyncSource() {}
563
564 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
565 std::lock_guard<std::mutex> lock(mCallbackMutex);
566 mCallback = callback;
567 }
568
569 virtual void onInjectSyncEvent(nsecs_t when) {
570 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700571 if (mCallback) {
572 mCallback->onVSyncEvent(when);
573 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700574 }
575
576 virtual void setVSyncEnabled(bool) {}
577 virtual void setPhaseOffset(nsecs_t) {}
578
579private:
580 std::mutex mCallbackMutex; // Protects the following
581 sp<VSyncSource::Callback> mCallback;
582};
583
Wei Wangf9b05ee2017-07-19 20:59:39 -0700584// Do not call property_set on main thread which will be blocked by init
585// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700586void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700587 ALOGI( "SurfaceFlinger's main thread ready to run. "
588 "Initializing graphics H/W...");
589
Thierry Strudel2924d012017-08-14 15:19:37 -0700590 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900591
Steven Thomasb02664d2017-07-26 18:48:28 -0700592 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800593
Steven Thomasb02664d2017-07-26 18:48:28 -0700594 // start the EventThread
595 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
596 vsyncPhaseOffsetNs, true, "app");
597 mEventThread = new EventThread(vsyncSrc, *this, false);
598 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
599 sfVsyncPhaseOffsetNs, true, "sf");
600 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
601 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800602
Steven Thomasb02664d2017-07-26 18:48:28 -0700603 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
604 struct sched_param param = {0};
605 param.sched_priority = 2;
606 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
607 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
608 }
609 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
610 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800611 }
612
Steven Thomasb02664d2017-07-26 18:48:28 -0700613 // Get a RenderEngine for the given display / config (can't fail)
Chia-I Wud4d9c6f2017-11-09 16:55:31 -0800614 mRenderEngine = RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
Steven Thomasb02664d2017-07-26 18:48:28 -0700615 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Chia-I Wud4d9c6f2017-11-09 16:55:31 -0800616 LOG_ALWAYS_FATAL_IF(mRenderEngine == nullptr, "couldn't create RenderEngine");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800617
Chia-I Wud4d9c6f2017-11-09 16:55:31 -0800618 // retrieve the EGL display/context that was selected/created
619 mEGLDisplay = mRenderEngine->getEGLDisplay();
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 mEGLContext = mRenderEngine->getEGLContext();
621
Steven Thomasb02664d2017-07-26 18:48:28 -0700622 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
623 "Starting with vr flinger active is not currently supported.");
624 mHwc.reset(new HWComposer(mHwcServiceName));
625 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800626
Steven Thomas050b2c82017-03-06 11:45:16 -0800627 if (useVrFlinger) {
628 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700629 // This callback is called from the vr flinger dispatch thread. We
630 // need to call signalTransaction(), which requires holding
631 // mStateLock when we're not on the main thread. Acquiring
632 // mStateLock from the vr flinger dispatch thread might trigger a
633 // deadlock in surface flinger (see b/66916578), so post a message
634 // to be handled on the main thread instead.
635 sp<LambdaMessage> message = new LambdaMessage([=]() {
636 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
637 mVrFlingerRequestsDisplay = requestDisplay;
638 signalTransaction();
639 });
640 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800641 };
642 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800643 mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
644 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800645 if (!mVrFlinger) {
646 ALOGE("Failed to start vrflinger");
647 }
648 }
649
Jamie Gennisd1700752013-10-14 12:22:52 -0700650 mEventControlThread = new EventControlThread(this);
651 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
652
Mathias Agopian92a979a2012-08-02 18:32:23 -0700653 // initialize our drawing state
654 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700655
Andy McFadden13a082e2012-08-24 10:16:42 -0700656 // set initial conditions (e.g. unblank default device)
657 initializeDisplays();
658
Dan Stoza4e637772016-07-28 13:31:51 -0700659 mRenderEngine->primeCache();
660
Wei Wangf9b05ee2017-07-19 20:59:39 -0700661 // Inform native graphics APIs whether the present timestamp is supported:
662 if (getHwComposer().hasCapability(
663 HWC2::Capability::PresentFenceIsNotReliable)) {
664 mStartPropertySetThread = new StartPropertySetThread(false);
665 } else {
666 mStartPropertySetThread = new StartPropertySetThread(true);
667 }
668
669 if (mStartPropertySetThread->Start() != NO_ERROR) {
670 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800671 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800672
Dan Stoza9e56aa02015-11-02 13:00:03 -0800673 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700674}
675
Romain Guy11d63f42017-07-20 12:47:14 -0700676void SurfaceFlinger::readPersistentProperties() {
677 char value[PROPERTY_VALUE_MAX];
678
679 property_get("persist.sys.sf.color_saturation", value, "1.0");
680 mSaturation = atof(value);
681 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100682
683 property_get("persist.sys.sf.native_mode", value, "0");
684 mForceNativeColorMode = atoi(value) == 1;
685 if (mForceNativeColorMode) {
686 ALOGV("Forcing native color mode");
687 }
Romain Guy11d63f42017-07-20 12:47:14 -0700688}
689
Mathias Agopiana67e4182012-06-19 17:26:12 -0700690void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800691 // Start boot animation service by setting a property mailbox
692 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700693 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800694 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700695 if (mStartPropertySetThread->join() != NO_ERROR) {
696 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800697 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700698}
699
Mathias Agopian875d8e12013-06-07 15:35:48 -0700700size_t SurfaceFlinger::getMaxTextureSize() const {
701 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700702}
703
Mathias Agopian875d8e12013-06-07 15:35:48 -0700704size_t SurfaceFlinger::getMaxViewportDims() const {
705 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700706}
707
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800708// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800709
Jamie Gennis582270d2011-08-17 18:19:00 -0700710bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800711 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800712 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800713 return authenticateSurfaceTextureLocked(bufferProducer);
714}
715
716bool SurfaceFlinger::authenticateSurfaceTextureLocked(
717 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800718 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700719 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800720}
721
Brian Anderson6b376712017-04-04 10:51:39 -0700722status_t SurfaceFlinger::getSupportedFrameTimestamps(
723 std::vector<FrameEvent>* outSupported) const {
724 *outSupported = {
725 FrameEvent::REQUESTED_PRESENT,
726 FrameEvent::ACQUIRE,
727 FrameEvent::LATCH,
728 FrameEvent::FIRST_REFRESH_START,
729 FrameEvent::LAST_REFRESH_START,
730 FrameEvent::GPU_COMPOSITION_DONE,
731 FrameEvent::DEQUEUE_READY,
732 FrameEvent::RELEASE,
733 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700734 ConditionalLock _l(mStateLock,
735 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700736 if (!getHwComposer().hasCapability(
737 HWC2::Capability::PresentFenceIsNotReliable)) {
738 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
739 }
740 return NO_ERROR;
741}
742
Dan Stoza7f7da322014-05-02 15:26:25 -0700743status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
744 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700745 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700746 return BAD_VALUE;
747 }
748
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500749 if (!display.get())
750 return NAME_NOT_FOUND;
751
Jesse Hall692c7232012-11-08 15:41:56 -0800752 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700753 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800754 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700755 type = i;
756 break;
757 }
758 }
759
760 if (type < 0) {
761 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700762 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700763
Mathias Agopian8b736f12012-08-13 17:54:26 -0700764 // TODO: Not sure if display density should handled by SF any longer
765 class Density {
766 static int getDensityFromProperty(char const* propName) {
767 char property[PROPERTY_VALUE_MAX];
768 int density = 0;
769 if (property_get(propName, property, NULL) > 0) {
770 density = atoi(property);
771 }
772 return density;
773 }
774 public:
775 static int getEmuDensity() {
776 return getDensityFromProperty("qemu.sf.lcd_density"); }
777 static int getBuildDensity() {
778 return getDensityFromProperty("ro.sf.lcd_density"); }
779 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700780
Dan Stoza7f7da322014-05-02 15:26:25 -0700781 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700782
Steven Thomas6d8110b2017-08-31 18:24:21 -0700783 ConditionalLock _l(mStateLock,
784 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800785 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700786 DisplayInfo info = DisplayInfo();
787
Dan Stoza9e56aa02015-11-02 13:00:03 -0800788 float xdpi = hwConfig->getDpiX();
789 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700790
791 if (type == DisplayDevice::DISPLAY_PRIMARY) {
792 // The density of the device is provided by a build property
793 float density = Density::getBuildDensity() / 160.0f;
794 if (density == 0) {
795 // the build doesn't provide a density -- this is wrong!
796 // use xdpi instead
797 ALOGE("ro.sf.lcd_density must be defined as a build property");
798 density = xdpi / 160.0f;
799 }
800 if (Density::getEmuDensity()) {
801 // if "qemu.sf.lcd_density" is specified, it overrides everything
802 xdpi = ydpi = density = Density::getEmuDensity();
803 density /= 160.0f;
804 }
805 info.density = density;
806
807 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700808 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000809 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700810 } else {
811 // TODO: where should this value come from?
812 static const int TV_DENSITY = 213;
813 info.density = TV_DENSITY / 160.0f;
814 info.orientation = 0;
815 }
816
Dan Stoza9e56aa02015-11-02 13:00:03 -0800817 info.w = hwConfig->getWidth();
818 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700819 info.xdpi = xdpi;
820 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800821 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900822 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800823
Andy McFadden91b2ca82014-06-13 14:04:23 -0700824 // This is how far in advance a buffer must be queued for
825 // presentation at a given time. If you want a buffer to appear
826 // on the screen at time N, you must submit the buffer before
827 // (N - presentationDeadline).
828 //
829 // Normally it's one full refresh period (to give SF a chance to
830 // latch the buffer), but this can be reduced by configuring a
831 // DispSync offset. Any additional delays introduced by the hardware
832 // composer or panel must be accounted for here.
833 //
834 // We add an additional 1ms to allow for processing time and
835 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800836 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800837 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700838
839 // All non-virtual displays are currently considered secure.
840 info.secure = true;
841
Michael Wright28f24d02016-07-12 13:30:53 -0700842 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700843 }
844
Dan Stoza7f7da322014-05-02 15:26:25 -0700845 return NO_ERROR;
846}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700847
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800848status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700849 DisplayStatInfo* stats) {
850 if (stats == NULL) {
851 return BAD_VALUE;
852 }
853
854 // FIXME for now we always return stats for the primary display
855 memset(stats, 0, sizeof(*stats));
856 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
857 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
858 return NO_ERROR;
859}
860
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700861int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800862 if (display == NULL) {
863 ALOGE("%s : display is NULL", __func__);
864 return BAD_VALUE;
865 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700866
867 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700868 if (device != NULL) {
869 return device->getActiveConfig();
870 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700871
Dan Stoza24a42e92015-03-09 10:04:11 -0700872 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700873}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700874
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700875void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
876 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
877 this);
878 int32_t type = hw->getDisplayType();
879 int currentMode = hw->getActiveConfig();
880
881 if (mode == currentMode) {
882 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
883 return;
884 }
885
886 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
887 ALOGW("Trying to set config for virtual display");
888 return;
889 }
890
891 hw->setActiveConfig(mode);
892 getHwComposer().setActiveConfig(type, mode);
893}
894
895status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
896 class MessageSetActiveConfig: public MessageBase {
897 SurfaceFlinger& mFlinger;
898 sp<IBinder> mDisplay;
899 int mMode;
900 public:
901 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
902 int mode) :
903 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
904 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700905 Vector<DisplayInfo> configs;
906 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700907 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700908 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700909 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700910 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700911 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700912 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
913 if (hw == NULL) {
914 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700915 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700916 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
917 ALOGW("Attempt to set active config = %d for virtual display",
918 mMode);
919 } else {
920 mFlinger.setActiveConfigInternal(hw, mMode);
921 }
922 return true;
923 }
924 };
925 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
926 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700927 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700928}
Michael Wright28f24d02016-07-12 13:30:53 -0700929status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
930 Vector<android_color_mode_t>* outColorModes) {
931 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
932 return BAD_VALUE;
933 }
934
935 if (!display.get()) {
936 return NAME_NOT_FOUND;
937 }
938
939 int32_t type = NAME_NOT_FOUND;
940 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
941 if (display == mBuiltinDisplays[i]) {
942 type = i;
943 break;
944 }
945 }
946
947 if (type < 0) {
948 return type;
949 }
950
Steven Thomas6d8110b2017-08-31 18:24:21 -0700951 std::vector<android_color_mode_t> modes;
952 {
953 ConditionalLock _l(mStateLock,
954 std::this_thread::get_id() != mMainThreadId);
955 modes = getHwComposer().getColorModes(type);
956 }
Michael Wright28f24d02016-07-12 13:30:53 -0700957 outColorModes->clear();
958 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
959
960 return NO_ERROR;
961}
962
963android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700964 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700965 if (device != nullptr) {
966 return device->getActiveColorMode();
967 }
968 return static_cast<android_color_mode_t>(BAD_VALUE);
969}
970
971void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
972 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700973 int32_t type = hw->getDisplayType();
974 android_color_mode_t currentMode = hw->getActiveColorMode();
975
976 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700977 return;
978 }
979
980 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
981 ALOGW("Trying to set config for virtual display");
982 return;
983 }
984
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600985 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
986 hw->getDisplayType());
987
Michael Wright28f24d02016-07-12 13:30:53 -0700988 hw->setActiveColorMode(mode);
989 getHwComposer().setActiveColorMode(type, mode);
990}
991
992
993status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
994 android_color_mode_t colorMode) {
995 class MessageSetActiveColorMode: public MessageBase {
996 SurfaceFlinger& mFlinger;
997 sp<IBinder> mDisplay;
998 android_color_mode_t mMode;
999 public:
1000 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1001 android_color_mode_t mode) :
1002 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1003 virtual bool handler() {
1004 Vector<android_color_mode_t> modes;
1005 mFlinger.getDisplayColorModes(mDisplay, &modes);
1006 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1007 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001008 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1009 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001010 return true;
1011 }
1012 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1013 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001014 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1015 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001016 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001017 ALOGW("Attempt to set active color mode %s %d for virtual display",
1018 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001019 } else {
1020 mFlinger.setActiveColorModeInternal(hw, mMode);
1021 }
1022 return true;
1023 }
1024 };
1025 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1026 postMessageSync(msg);
1027 return NO_ERROR;
1028}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001029
Svetoslavd85084b2014-03-20 10:28:31 -07001030status_t SurfaceFlinger::clearAnimationFrameStats() {
1031 Mutex::Autolock _l(mStateLock);
1032 mAnimFrameTracker.clearStats();
1033 return NO_ERROR;
1034}
1035
1036status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1037 Mutex::Autolock _l(mStateLock);
1038 mAnimFrameTracker.getStats(outStats);
1039 return NO_ERROR;
1040}
1041
Dan Stozac4f471e2016-03-24 09:31:08 -07001042status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1043 HdrCapabilities* outCapabilities) const {
1044 Mutex::Autolock _l(mStateLock);
1045
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001046 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001047 if (displayDevice == nullptr) {
1048 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1049 return BAD_VALUE;
1050 }
1051
1052 std::unique_ptr<HdrCapabilities> capabilities =
1053 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1054 if (capabilities) {
1055 std::swap(*outCapabilities, *capabilities);
1056 } else {
1057 return BAD_VALUE;
1058 }
1059
1060 return NO_ERROR;
1061}
1062
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001063status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001064 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1065 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001066
Chia-I Wu90f669f2017-10-05 14:24:41 -07001067 if (mInjectVSyncs == enable) {
1068 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001069 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001070
1071 if (enable) {
1072 ALOGV("VSync Injections enabled");
1073 if (mVSyncInjector.get() == nullptr) {
1074 mVSyncInjector = new InjectVSyncSource();
1075 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1076 }
1077 mEventQueue.setEventThread(mInjectorEventThread);
1078 } else {
1079 ALOGV("VSync Injections disabled");
1080 mEventQueue.setEventThread(mSFEventThread);
1081 }
1082
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001083 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001084 });
1085 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001086 return NO_ERROR;
1087}
1088
1089status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001090 Mutex::Autolock _l(mStateLock);
1091
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001092 if (!mInjectVSyncs) {
1093 ALOGE("VSync Injections not enabled");
1094 return BAD_VALUE;
1095 }
1096 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1097 ALOGV("Injecting VSync inside SurfaceFlinger");
1098 mVSyncInjector->onInjectSyncEvent(when);
1099 }
1100 return NO_ERROR;
1101}
1102
Kalle Raitaa099a242017-01-11 11:17:29 -08001103status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1104 IPCThreadState* ipc = IPCThreadState::self();
1105 const int pid = ipc->getCallingPid();
1106 const int uid = ipc->getCallingUid();
1107 if ((uid != AID_SHELL) &&
1108 !PermissionCache::checkPermission(sDump, pid, uid)) {
1109 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1110 return PERMISSION_DENIED;
1111 }
1112
1113 // Try to acquire a lock for 1s, fail gracefully
1114 const status_t err = mStateLock.timedLock(s2ns(1));
1115 const bool locked = (err == NO_ERROR);
1116 if (!locked) {
1117 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1118 return TIMED_OUT;
1119 }
1120
1121 outLayers->clear();
1122 mCurrentState.traverseInZOrder([&](Layer* layer) {
1123 outLayers->push_back(layer->getLayerDebugInfo());
1124 });
1125
1126 mStateLock.unlock();
1127 return NO_ERROR;
1128}
1129
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001130// ----------------------------------------------------------------------------
1131
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001132sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1133 ISurfaceComposer::VsyncSource vsyncSource) {
1134 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1135 return mSFEventThread->createEventConnection();
1136 } else {
1137 return mEventThread->createEventConnection();
1138 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001139}
1140
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001141// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001142
1143void SurfaceFlinger::waitForEvent() {
1144 mEventQueue.waitMessage();
1145}
1146
1147void SurfaceFlinger::signalTransaction() {
1148 mEventQueue.invalidate();
1149}
1150
1151void SurfaceFlinger::signalLayerUpdate() {
1152 mEventQueue.invalidate();
1153}
1154
1155void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001156 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001157 mEventQueue.refresh();
1158}
1159
1160status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001161 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001162 return mEventQueue.postMessage(msg, reltime);
1163}
1164
1165status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001166 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001167 status_t res = mEventQueue.postMessage(msg, reltime);
1168 if (res == NO_ERROR) {
1169 msg->wait();
1170 }
1171 return res;
1172}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001173
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001174void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001175 do {
1176 waitForEvent();
1177 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001178}
1179
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001180void SurfaceFlinger::enableHardwareVsync() {
1181 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001182 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001183 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001184 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1185 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001187 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001188}
1189
Jesse Hall948fe0c2013-10-14 12:56:09 -07001190void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001191 Mutex::Autolock _l(mHWVsyncLock);
1192
Jesse Hall948fe0c2013-10-14 12:56:09 -07001193 if (makeAvailable) {
1194 mHWVsyncAvailable = true;
1195 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001196 // Hardware vsync is not currently available, so abort the resync
1197 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001198 return;
1199 }
1200
Dan Stoza9e56aa02015-11-02 13:00:03 -08001201 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1202 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001203
1204 mPrimaryDispSync.reset();
1205 mPrimaryDispSync.setPeriod(period);
1206
1207 if (!mPrimaryHWVsyncEnabled) {
1208 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001209 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1210 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001211 mPrimaryHWVsyncEnabled = true;
1212 }
1213}
1214
Jesse Hall948fe0c2013-10-14 12:56:09 -07001215void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001216 Mutex::Autolock _l(mHWVsyncLock);
1217 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001218 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1219 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220 mPrimaryDispSync.endResync();
1221 mPrimaryHWVsyncEnabled = false;
1222 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001223 if (makeUnavailable) {
1224 mHWVsyncAvailable = false;
1225 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001226}
1227
Tim Murray4a4e4a22016-04-19 16:29:23 +00001228void SurfaceFlinger::resyncWithRateLimit() {
1229 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001230
1231 // No explicit locking is needed here since EventThread holds a lock while calling this method
1232 static nsecs_t sLastResyncAttempted = 0;
1233 const nsecs_t now = systemTime();
1234 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001235 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001236 }
Dan Stoza57164302017-05-08 14:03:54 -07001237 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001238}
1239
Steven Thomasb02664d2017-07-26 18:48:28 -07001240void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1241 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001242 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001243 // Ignore any vsyncs from a previous hardware composer.
1244 if (sequenceId != mComposerSequenceId) {
1245 return;
1246 }
1247
1248 int32_t type;
1249 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001250 return;
1251 }
1252
Jamie Gennisd1700752013-10-14 12:22:52 -07001253 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254
Jamie Gennisd1700752013-10-14 12:22:52 -07001255 { // Scope for the lock
1256 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001257 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001258 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001259 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001260 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001261
1262 if (needsHwVsync) {
1263 enableHardwareVsync();
1264 } else {
1265 disableHardwareVsync(false);
1266 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001267}
1268
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001269void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001270 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001271 *compositorTiming = mCompositorTiming;
1272}
1273
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001274void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001275 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001276 wp<IBinder> token = mBuiltinDisplays[type];
1277
1278 // All non-virtual displays are currently considered secure.
1279 const bool isSecure = true;
1280
1281 sp<IGraphicBufferProducer> producer;
1282 sp<IGraphicBufferConsumer> consumer;
1283 BufferQueue::createBufferQueue(&producer, &consumer);
1284
1285 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1286
1287 bool hasWideColorModes = false;
1288 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1289 for (android_color_mode_t colorMode : modes) {
1290 switch (colorMode) {
1291 case HAL_COLOR_MODE_DISPLAY_P3:
1292 case HAL_COLOR_MODE_ADOBE_RGB:
1293 case HAL_COLOR_MODE_DCI_P3:
1294 hasWideColorModes = true;
1295 break;
1296 default:
1297 break;
1298 }
1299 }
Romain Guy54f154a2017-10-24 21:40:32 +01001300 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001301 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1302 token, fbs, producer, mRenderEngine->getEGLConfig(),
Romain Guy54f154a2017-10-24 21:40:32 +01001303 useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001304 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001305 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001306 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001307 defaultColorMode = HAL_COLOR_MODE_SRGB;
1308 }
1309 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001310 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001311
1312 // Add the primary display token to mDrawingState so we don't try to
1313 // recreate the DisplayDevice for the primary display.
1314 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1315
1316 // make the GLContext current so that we can create textures when creating
1317 // Layers (which may happens before we render something)
1318 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001319}
1320
Steven Thomasb02664d2017-07-26 18:48:28 -07001321void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1322 hwc2_display_t display, HWC2::Connection connection,
1323 bool primaryDisplay) {
1324 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1325 sequenceId, display,
1326 connection == HWC2::Connection::Connected ?
1327 "connected" : "disconnected",
1328 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001329
Steven Thomasb02664d2017-07-26 18:48:28 -07001330 // Only lock if we're not on the main thread. This function is normally
1331 // called on a hwbinder thread, but for the primary display it's called on
1332 // the main thread with the state lock already held, so don't attempt to
1333 // acquire it here.
1334 ConditionalLock lock(mStateLock,
1335 std::this_thread::get_id() != mMainThreadId);
1336
1337 if (primaryDisplay) {
1338 mHwc->onHotplug(display, connection);
1339 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1340 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001341 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001342 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001343 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 if (sequenceId != mComposerSequenceId) {
1345 return;
1346 }
1347 if (mHwc->isUsingVrComposer()) {
1348 ALOGE("External displays are not supported by the vr hardware composer.");
1349 return;
1350 }
1351 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001352 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001353 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001354 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001355 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001356 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1357 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001358 }
1359 setTransactionFlags(eDisplayTransactionNeeded);
1360
Andy McFadden9e9689c2012-10-10 18:17:51 -07001361 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001362 }
Mathias Agopian86303202012-07-24 22:46:10 -07001363}
1364
Steven Thomasb02664d2017-07-26 18:48:28 -07001365void SurfaceFlinger::onRefreshReceived(int sequenceId,
1366 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001367 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001368 if (sequenceId != mComposerSequenceId) {
1369 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001370 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001371 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001372}
1373
Dan Stoza9e56aa02015-11-02 13:00:03 -08001374void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001375 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001377 getHwComposer().setVsyncEnabled(disp,
1378 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001379}
1380
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001381// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001382void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001383 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001384 // Clear the drawing state so that the logic inside of
1385 // handleTransactionLocked will fire. It will determine the delta between
1386 // mCurrentState and mDrawingState and re-apply all changes when we make the
1387 // transition.
1388 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001389 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001390 mDisplays.clear();
1391}
1392
Steven Thomas050b2c82017-03-06 11:45:16 -08001393void SurfaceFlinger::updateVrFlinger() {
1394 if (!mVrFlinger)
1395 return;
1396 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1397 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001398 return;
1399 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400
Steven Thomasb02664d2017-07-26 18:48:28 -07001401 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1402 ALOGE("Vr flinger is only supported for remote hardware composer"
1403 " service connections. Ignoring request to transition to vr"
1404 " flinger.");
1405 mVrFlingerRequestsDisplay = false;
1406 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001407 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001408
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001409 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 int currentDisplayPowerMode = getDisplayDeviceLocked(
1412 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001413
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001415 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 resetDisplayState();
1419 mHwc.reset(); // Delete the current instance before creating the new one
1420 mHwc.reset(new HWComposer(
1421 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1422 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001423
Steven Thomasb02664d2017-07-26 18:48:28 -07001424 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1425 "Switched to non-remote hardware composer");
1426
1427 if (vrFlingerRequestsDisplay) {
1428 mVrFlinger->GrantDisplayOwnership();
1429 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432
1433 mVisibleRegionsDirty = true;
1434 invalidateHwcGeometry();
1435
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001436 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001437 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1438 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1439 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001440
Steven Thomasb02664d2017-07-26 18:48:28 -07001441 // Reset the timing values to account for the period of the swapped in HWC
1442 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1443 const nsecs_t period = activeConfig->getVsyncPeriod();
1444 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001445
Steven Thomasb02664d2017-07-26 18:48:28 -07001446 // Use phase of 0 since phase is not known.
1447 // Use latency of 0, which will snap to the ideal latency.
1448 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001449
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001450 android_atomic_or(1, &mRepaintEverything);
1451 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001452}
1453
Mathias Agopian4fec8732012-06-29 14:12:52 -07001454void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001455 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001456 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001457 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001458 bool frameMissed = !mHadClientComposition &&
1459 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001460 (mPreviousPresentFence->getSignalTime() ==
1461 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001462 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001463 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001464 signalLayerUpdate();
1465 break;
1466 }
1467
Steven Thomas050b2c82017-03-06 11:45:16 -08001468 // Now that we're going to make it to the handleMessageTransaction()
1469 // call below it's safe to call updateVrFlinger(), which will
1470 // potentially trigger a display handoff.
1471 updateVrFlinger();
1472
Dan Stoza6b9454d2014-11-07 16:00:59 -08001473 bool refreshNeeded = handleMessageTransaction();
1474 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001475 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001476 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001477 // Signal a refresh if a transaction modified the window state,
1478 // a new buffer was latched, or if HWC has requested a full
1479 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001480 signalRefresh();
1481 }
1482 break;
1483 }
1484 case MessageQueue::REFRESH: {
1485 handleMessageRefresh();
1486 break;
1487 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001488 }
1489}
1490
Dan Stoza6b9454d2014-11-07 16:00:59 -08001491bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001492 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001493 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001494 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001495 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001496 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001497 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001498}
1499
Dan Stoza6b9454d2014-11-07 16:00:59 -08001500bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001501 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001502 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001503}
1504
1505void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001506 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001507
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001508 mRefreshPending = false;
1509
Pablo Ceballos40845df2016-01-25 17:41:15 -08001510 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001511
Brian Andersond6927fb2016-07-23 23:37:30 -07001512 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001513 rebuildLayerStacks();
1514 setUpHWComposer();
1515 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001516 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001517 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001518 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001519
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001520 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001521
1522 mHadClientComposition = false;
1523 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1524 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1525 mHadClientComposition = mHadClientComposition ||
1526 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1527 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001528
Dan Stoza9e56aa02015-11-02 13:00:03 -08001529 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001530}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001531
Mathias Agopiancd60f992012-08-16 16:28:27 -07001532void SurfaceFlinger::doDebugFlashRegions()
1533{
1534 // is debugging enabled
1535 if (CC_LIKELY(!mDebugRegion))
1536 return;
1537
1538 const bool repaintEverything = mRepaintEverything;
1539 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1540 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001541 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001542 // transform the dirty region into this screen's coordinate space
1543 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1544 if (!dirtyRegion.isEmpty()) {
1545 // redraw the whole screen
1546 doComposeSurfaces(hw, Region(hw->bounds()));
1547
1548 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001549 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001550 RenderEngine& engine(getRenderEngine());
1551 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1552
Mathias Agopianda27af92012-09-13 18:17:13 -07001553 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001554 }
1555 }
1556 }
1557
1558 postFramebuffer();
1559
1560 if (mDebugRegion > 1) {
1561 usleep(mDebugRegion * 1000);
1562 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001563
Dan Stoza9e56aa02015-11-02 13:00:03 -08001564 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001565 auto& displayDevice = mDisplays[displayId];
1566 if (!displayDevice->isDisplayOn()) {
1567 continue;
1568 }
1569
1570 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001571 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1572 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001573 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001574}
1575
Adrian Roos1e1a1282017-11-01 19:05:31 +01001576void SurfaceFlinger::doTracing(const char* where) {
1577 ATRACE_CALL();
1578 ATRACE_NAME(where);
1579 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001580 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001581 }
1582}
1583
Brian Andersond6927fb2016-07-23 23:37:30 -07001584void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001585{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001586 ATRACE_CALL();
1587 ALOGV("preComposition");
1588
Mathias Agopiancd60f992012-08-16 16:28:27 -07001589 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001590 mDrawingState.traverseInZOrder([&](Layer* layer) {
1591 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592 needExtraInvalidate = true;
1593 }
Robert Carr2047fae2016-11-28 14:09:09 -08001594 });
1595
Mathias Agopiancd60f992012-08-16 16:28:27 -07001596 if (needExtraInvalidate) {
1597 signalLayerUpdate();
1598 }
1599}
1600
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001601void SurfaceFlinger::updateCompositorTiming(
1602 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1603 std::shared_ptr<FenceTime>& presentFenceTime) {
1604 // Update queue of past composite+present times and determine the
1605 // most recently known composite to present latency.
1606 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1607 nsecs_t compositeToPresentLatency = -1;
1608 while (!mCompositePresentTimes.empty()) {
1609 CompositePresentTime& cpt = mCompositePresentTimes.front();
1610 // Cached values should have been updated before calling this method,
1611 // which helps avoid duplicate syscalls.
1612 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1613 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1614 break;
1615 }
1616 compositeToPresentLatency = displayTime - cpt.composite;
1617 mCompositePresentTimes.pop();
1618 }
1619
1620 // Don't let mCompositePresentTimes grow unbounded, just in case.
1621 while (mCompositePresentTimes.size() > 16) {
1622 mCompositePresentTimes.pop();
1623 }
1624
Brian Andersond0010582017-03-07 13:20:31 -08001625 setCompositorTimingSnapped(
1626 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1627}
1628
1629void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1630 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001631 // Integer division and modulo round toward 0 not -inf, so we need to
1632 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001633 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1635 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1636
Brian Andersond0010582017-03-07 13:20:31 -08001637 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1638 if (idealLatency <= 0) {
1639 idealLatency = vsyncInterval;
1640 }
1641
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642 // Snap the latency to a value that removes scheduling jitter from the
1643 // composition and present times, which often have >1ms of jitter.
1644 // Reducing jitter is important if an app attempts to extrapolate
1645 // something (such as user input) to an accurate diasplay time.
1646 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1647 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001648 nsecs_t bias = vsyncInterval / 2;
1649 int64_t extraVsyncs =
1650 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1651 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1652 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653
Brian Andersond0010582017-03-07 13:20:31 -08001654 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001655 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1656 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001657 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001658}
1659
1660void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001661{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001662 ATRACE_CALL();
1663 ALOGV("postComposition");
1664
Brian Anderson3546a3f2016-07-14 11:51:14 -07001665 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001666 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001667 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001668 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001669 }
1670
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001671 // |mStateLock| not needed as we are on the main thread
1672 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001673
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001674 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001675 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1676 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1677 glCompositionDoneFenceTime =
1678 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1679 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1680 } else {
1681 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1682 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001683
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001684 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001685 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1686 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1687 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001688
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001689 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1690 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1691
1692 // We use the refreshStartTime which might be sampled a little later than
1693 // when we started doing work for this frame, but that should be okay
1694 // since updateCompositorTiming has snapping logic.
1695 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001696 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001697 CompositorTiming compositorTiming;
1698 {
1699 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1700 compositorTiming = mCompositorTiming;
1701 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001702
Robert Carr2047fae2016-11-28 14:09:09 -08001703 mDrawingState.traverseInZOrder([&](Layer* layer) {
1704 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001705 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001706 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001707 recordBufferingStats(layer->getName().string(),
1708 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001709 }
Robert Carr2047fae2016-11-28 14:09:09 -08001710 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001711
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001712 if (presentFenceTime->isValid()) {
1713 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001714 enableHardwareVsync();
1715 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001716 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001717 }
1718 }
1719
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001720 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001721 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001722 enableHardwareVsync();
1723 }
1724 }
1725
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001726 if (mAnimCompositionPending) {
1727 mAnimCompositionPending = false;
1728
Brian Anderson4e606e32017-03-16 15:34:57 -07001729 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001730 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001731 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001732 } else {
1733 // The HWC doesn't support present fences, so use the refresh
1734 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001735 nsecs_t presentTime =
1736 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001737 mAnimFrameTracker.setActualPresentTime(presentTime);
1738 }
1739 mAnimFrameTracker.advanceFrame();
1740 }
Dan Stozab90cf072015-03-05 11:05:59 -08001741
1742 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1743 return;
1744 }
1745
1746 nsecs_t currentTime = systemTime();
1747 if (mHasPoweredOff) {
1748 mHasPoweredOff = false;
1749 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001750 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001751 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001752 if (numPeriods < NUM_BUCKETS - 1) {
1753 mFrameBuckets[numPeriods] += elapsedTime;
1754 } else {
1755 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1756 }
1757 mTotalTime += elapsedTime;
1758 }
1759 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001760}
1761
1762void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001763 ATRACE_CALL();
1764 ALOGV("rebuildLayerStacks");
1765
Mathias Agopiancd60f992012-08-16 16:28:27 -07001766 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001767 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001768 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001769 mVisibleRegionsDirty = false;
1770 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001771
Jeff Sharkey76488112017-02-27 14:15:18 -07001772 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1773 Region opaqueRegion;
1774 Region dirtyRegion;
1775 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001776 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001777 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1778 const Transform& tr(displayDevice->getTransform());
1779 const Rect bounds(displayDevice->getBounds());
1780 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001781 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001782
Jeff Sharkey76488112017-02-27 14:15:18 -07001783 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001784 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001785 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1786 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001787 Region drawRegion(tr.transform(
1788 layer->visibleNonTransparentRegion));
1789 drawRegion.andSelf(bounds);
1790 if (!drawRegion.isEmpty()) {
1791 layersSortedByZ.add(layer);
1792 } else {
1793 // Clear out the HWC layer if this layer was
1794 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001795 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001796 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001797 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001798 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001799 // WM changes displayDevice->layerStack upon sleep/awake.
1800 // Here we make sure we delete the HWC layers even if
1801 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001802 hwcLayerDestroyed = layer->destroyHwcLayer(
1803 displayDevice->getHwcDisplayId());
1804 }
1805
1806 // If a layer is not going to get a release fence because
1807 // it is invisible, but it is also going to release its
1808 // old buffer, add it to the list of layers needing
1809 // fences.
1810 if (hwcLayerDestroyed) {
1811 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1812 mLayersWithQueuedFrames.cend(), layer);
1813 if (found != mLayersWithQueuedFrames.cend()) {
1814 layersNeedingFences.add(layer);
1815 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001816 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001817 });
1818 }
1819 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001820 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001821 displayDevice->undefinedRegion.set(bounds);
1822 displayDevice->undefinedRegion.subtractSelf(
1823 tr.transform(opaqueRegion));
1824 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001825 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001826 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001827}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001828
Romain Guy0147a172017-06-01 13:53:56 -07001829mat4 SurfaceFlinger::computeSaturationMatrix() const {
1830 if (mSaturation == 1.0f) {
1831 return mat4();
1832 }
1833
1834 // Rec.709 luma coefficients
1835 float3 luminance{0.213f, 0.715f, 0.072f};
1836 luminance *= 1.0f - mSaturation;
1837 return mat4(
1838 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1839 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1840 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1841 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1842 );
1843}
1844
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001845// pickColorMode translates a given dataspace into the best available color mode.
1846// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001847android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001848 if (mForceNativeColorMode) {
1849 return HAL_COLOR_MODE_NATIVE;
1850 }
1851
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001852 switch (dataSpace) {
1853 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1854 // system expects.
1855 case HAL_DATASPACE_UNKNOWN:
1856 case HAL_DATASPACE_SRGB:
1857 case HAL_DATASPACE_V0_SRGB:
1858 return HAL_COLOR_MODE_SRGB;
1859 break;
1860
1861 case HAL_DATASPACE_DISPLAY_P3:
1862 return HAL_COLOR_MODE_DISPLAY_P3;
1863 break;
1864
1865 default:
1866 // TODO (courtneygo): Do we want to assert an error here?
1867 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1868 dataSpace);
1869 return HAL_COLOR_MODE_SRGB;
1870 break;
1871 }
1872}
1873
Romain Guy0147a172017-06-01 13:53:56 -07001874android_dataspace SurfaceFlinger::bestTargetDataSpace(
1875 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001876 // Only support sRGB and Display-P3 right now.
1877 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1878 return HAL_DATASPACE_DISPLAY_P3;
1879 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001880 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1881 return HAL_DATASPACE_DISPLAY_P3;
1882 }
1883 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1884 return HAL_DATASPACE_DISPLAY_P3;
1885 }
1886
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001887 return HAL_DATASPACE_V0_SRGB;
1888}
1889
Mathias Agopiancd60f992012-08-16 16:28:27 -07001890void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 ATRACE_CALL();
1892 ALOGV("setUpHWComposer");
1893
Jesse Hall028dc8f2013-08-20 16:35:32 -07001894 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001895 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1896 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1897 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1898
1899 // If nothing has changed (!dirty), don't recompose.
1900 // If something changed, but we don't currently have any visible layers,
1901 // and didn't when we last did a composition, then skip it this time.
1902 // The second rule does two things:
1903 // - When all layers are removed from a display, we'll emit one black
1904 // frame, then nothing more until we get new layers.
1905 // - When a display is created with a private layer stack, we won't
1906 // emit any black frames until a layer is added to the layer stack.
1907 bool mustRecompose = dirty && !(empty && wasEmpty);
1908
1909 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1910 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1911 mustRecompose ? "doing" : "skipping",
1912 dirty ? "+" : "-",
1913 empty ? "+" : "-",
1914 wasEmpty ? "+" : "-");
1915
Dan Stoza71433162014-02-04 16:22:36 -08001916 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001917
1918 if (mustRecompose) {
1919 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1920 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001921 }
1922
Dan Stoza9e56aa02015-11-02 13:00:03 -08001923 // build the h/w work list
1924 if (CC_UNLIKELY(mGeometryInvalid)) {
1925 mGeometryInvalid = false;
1926 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1927 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1928 const auto hwcId = displayDevice->getHwcDisplayId();
1929 if (hwcId >= 0) {
1930 const Vector<sp<Layer>>& currentLayers(
1931 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001932 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001933 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001935 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001936 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001937 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001938 }
1939 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001940
Robert Carrae060832016-11-28 10:51:00 -08001941 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001942 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001943 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001944 }
1945 }
1946 }
1947 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001948 }
Riley Andrews03414a12014-07-01 14:22:59 -07001949
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001950
Romain Guy0147a172017-06-01 13:53:56 -07001951 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001952
Dan Stoza9e56aa02015-11-02 13:00:03 -08001953 // Set the per-frame data
1954 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1955 auto& displayDevice = mDisplays[displayId];
1956 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001957
Dan Stoza9e56aa02015-11-02 13:00:03 -08001958 if (hwcId < 0) {
1959 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001960 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001961 if (colorMatrix != mPreviousColorMatrix) {
1962 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1963 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1964 "display %zd: %d", displayId, result);
1965 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001966 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
chaviwc9232ed2017-11-14 15:31:15 -08001967 if (layer->getForceClientComposition(hwcId)) {
1968 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1969 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1970 continue;
1971 }
1972
Dan Stoza9e56aa02015-11-02 13:00:03 -08001973 layer->setPerFrameData(displayDevice);
1974 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001975
1976 if (hasWideColorDisplay) {
1977 android_color_mode newColorMode;
1978 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1979
1980 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1981 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1982 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1983 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1984 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1985 }
1986 newColorMode = pickColorMode(newDataSpace);
1987
Thierry Strudel2924d012017-08-14 15:19:37 -07001988 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001989 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001990 }
1991
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001992 mPreviousColorMatrix = colorMatrix;
1993
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001995 auto& displayDevice = mDisplays[displayId];
1996 if (!displayDevice->isDisplayOn()) {
1997 continue;
1998 }
1999
2000 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002001 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2002 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002003 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002004}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002005
Mathias Agopiancd60f992012-08-16 16:28:27 -07002006void SurfaceFlinger::doComposition() {
2007 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002008 ALOGV("doComposition");
2009
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002010 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002011 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002012 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002013 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002014 // transform the dirty region into this screen's coordinate space
2015 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002016
2017 // repaint the framebuffer (if needed)
2018 doDisplayComposition(hw, dirtyRegion);
2019
Mathias Agopiancd60f992012-08-16 16:28:27 -07002020 hw->dirtyRegion.clear();
2021 hw->flip(hw->swapRegion);
2022 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07002023 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002024 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002025 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002026}
2027
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002028void SurfaceFlinger::postFramebuffer()
2029{
Mathias Agopian841cde52012-03-01 15:44:37 -08002030 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002031 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002032
Mathias Agopiana44b0412011-10-16 18:46:35 -07002033 const nsecs_t now = systemTime();
2034 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002035
Dan Stoza9e56aa02015-11-02 13:00:03 -08002036 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2037 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002038 if (!displayDevice->isDisplayOn()) {
2039 continue;
2040 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002041 const auto hwcId = displayDevice->getHwcDisplayId();
2042 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002043 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002044 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002045 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002046 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002047 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002048 // The layer buffer from the previous frame (if any) is released
2049 // by HWC only when the release fence from this frame (if any) is
2050 // signaled. Always get the release fence from HWC first.
2051 auto hwcLayer = layer->getHwcLayer(hwcId);
2052 sp<Fence> releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2053
2054 // If the layer was client composited in the previous frame, we
2055 // need to merge with the previous client target acquire fence.
2056 // Since we do not track that, always merge with the current
2057 // client target acquire fence when it is available, even though
2058 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002059 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002060 releaseFence = Fence::merge("LayerRelease", releaseFence,
2061 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002062 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002063
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 layer->onLayerDisplayed(releaseFence);
2065 }
Chia-I Wu83806892017-11-16 10:50:20 -08002066
2067 // We've got a list of layers needing fences, that are disjoint with
2068 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2069 // supply them with the present fence.
2070 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
2071 sp<Fence> presentFence = mHwc->getPresentFence(hwcId);
2072 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2073 layer->onLayerDisplayed(presentFence);
2074 }
2075 }
2076
Dan Stoza9e56aa02015-11-02 13:00:03 -08002077 if (hwcId >= 0) {
2078 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002079 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002080 }
2081
Mathias Agopiana44b0412011-10-16 18:46:35 -07002082 mLastSwapBufferTime = systemTime() - now;
2083 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002084
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002085 // |mStateLock| not needed as we are on the main thread
2086 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002087 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2088 logFrameStats();
2089 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002090}
2091
Mathias Agopian87baae12012-07-31 12:38:26 -07002092void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093{
Mathias Agopian841cde52012-03-01 15:44:37 -08002094 ATRACE_CALL();
2095
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002096 // here we keep a copy of the drawing state (that is the state that's
2097 // going to be overwritten by handleTransactionLocked()) outside of
2098 // mStateLock so that the side-effects of the State assignment
2099 // don't happen with mStateLock held (which can cause deadlocks).
2100 State drawingState(mDrawingState);
2101
Mathias Agopianca4d3602011-05-19 15:38:14 -07002102 Mutex::Autolock _l(mStateLock);
2103 const nsecs_t now = systemTime();
2104 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002105
Mathias Agopianca4d3602011-05-19 15:38:14 -07002106 // Here we're guaranteed that some transaction flags are set
2107 // so we can call handleTransactionLocked() unconditionally.
2108 // We call getTransactionFlags(), which will also clear the flags,
2109 // with mStateLock held to guarantee that mCurrentState won't change
2110 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002111
Mathias Agopiane57f2922012-08-09 16:29:12 -07002112 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002113 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002114
Mathias Agopianca4d3602011-05-19 15:38:14 -07002115 mLastTransactionTime = systemTime() - now;
2116 mDebugInTransaction = 0;
2117 invalidateHwcGeometry();
2118 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002119}
2120
Mathias Agopian87baae12012-07-31 12:38:26 -07002121void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002122{
Dan Stoza7dde5992015-05-22 09:51:44 -07002123 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002124 mCurrentState.traverseInZOrder([](Layer* layer) {
2125 layer->notifyAvailableFrames();
2126 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002127
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002128 /*
2129 * Traversal of the children
2130 * (perform the transaction for each of them if needed)
2131 */
2132
Mathias Agopian3559b072012-08-15 13:46:03 -07002133 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002134 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002135 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002136 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002137
2138 const uint32_t flags = layer->doTransaction(0);
2139 if (flags & Layer::eVisibleRegion)
2140 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002141 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002142 }
2143
2144 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002145 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002146 */
2147
Mathias Agopiane57f2922012-08-09 16:29:12 -07002148 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002149 // here we take advantage of Vector's copy-on-write semantics to
2150 // improve performance by skipping the transaction entirely when
2151 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002152 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2153 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002154 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002155 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002156 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002157 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002158
2159 // find the displays that were removed
2160 // (ie: in drawing state but not in current state)
2161 // also handle displays that changed
2162 // (ie: displays that are in both lists)
2163 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002164 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2165 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002166 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002167 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002168 // Call makeCurrent() on the primary display so we can
2169 // be sure that nothing associated with this display
2170 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002171 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002172 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002173 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002174 if (hw != NULL)
2175 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002176 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002177 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002178 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002179 } else {
2180 ALOGW("trying to remove the main display");
2181 }
2182 } else {
2183 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002184 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002185 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002186 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2187 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002188 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002189 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002190 // recreating the DisplayDevice, so we just remove it
2191 // from the drawing state, so that it get re-added
2192 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002193 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002194 if (hw != NULL)
2195 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002196 mDisplays.removeItem(display);
2197 mDrawingState.displays.removeItemsAt(i);
2198 dc--; i--;
2199 // at this point we must loop to the next item
2200 continue;
2201 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002202
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002203 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002204 if (disp != NULL) {
2205 if (state.layerStack != draw[i].layerStack) {
2206 disp->setLayerStack(state.layerStack);
2207 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002208 if ((state.orientation != draw[i].orientation)
2209 || (state.viewport != draw[i].viewport)
2210 || (state.frame != draw[i].frame))
2211 {
2212 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002213 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002214 }
Michael Lentine47e45402014-07-18 15:34:25 -07002215 if (state.width != draw[i].width || state.height != draw[i].height) {
2216 disp->setDisplaySize(state.width, state.height);
2217 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002218 }
2219 }
2220 }
2221
2222 // find displays that were added
2223 // (ie: in current state but not in drawing state)
2224 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002225 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002226 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002227
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002228 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002229 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002230 sp<IGraphicBufferProducer> bqProducer;
2231 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002232 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002233
Dan Stoza9e56aa02015-11-02 13:00:03 -08002234 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002235 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002236 // Virtual displays without a surface are dormant:
2237 // they have external state (layer stack, projection,
2238 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002239 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002240
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002241 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002242 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002243 int width = 0;
2244 int status = state.surface->query(
2245 NATIVE_WINDOW_WIDTH, &width);
2246 ALOGE_IF(status != NO_ERROR,
2247 "Unable to query width (%d)", status);
2248 int height = 0;
2249 status = state.surface->query(
2250 NATIVE_WINDOW_HEIGHT, &height);
2251 ALOGE_IF(status != NO_ERROR,
2252 "Unable to query height (%d)", status);
2253 int intFormat = 0;
2254 status = state.surface->query(
2255 NATIVE_WINDOW_FORMAT, &intFormat);
2256 ALOGE_IF(status != NO_ERROR,
2257 "Unable to query format (%d)", status);
2258 auto format = static_cast<android_pixel_format_t>(
2259 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002260
Dan Stoza8cf150a2016-08-02 10:27:31 -07002261 mHwc->allocateVirtualDisplay(width, height, &format,
2262 &hwcId);
2263 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002264
Dan Stoza5cf424b2016-05-20 14:02:39 -07002265 // TODO: Plumb requested format back up to consumer
2266
Dan Stoza9e56aa02015-11-02 13:00:03 -08002267 sp<VirtualDisplaySurface> vds =
2268 new VirtualDisplaySurface(*mHwc,
2269 hwcId, state.surface, bqProducer,
2270 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002271
2272 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002273 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002274 }
2275 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002276 ALOGE_IF(state.surface!=NULL,
2277 "adding a supported display, but rendering "
2278 "surface is provided (%p), ignoring it",
2279 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002280
2281 hwcId = state.type;
2282 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2283 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002284 }
2285
2286 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002287 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002288 sp<DisplayDevice> hw =
2289 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2290 dispSurface, producer,
2291 mRenderEngine->getEGLConfig(),
2292 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002293 hw->setLayerStack(state.layerStack);
2294 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002295 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002296 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002297 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002298 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002299 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002300 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002301 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002302 }
2303 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002304 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002305 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002306
Mathias Agopian84300952012-11-21 16:02:13 -08002307 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2308 // The transform hint might have changed for some layers
2309 // (either because a display has changed, or because a layer
2310 // as changed).
2311 //
2312 // Walk through all the layers in currentLayers,
2313 // and update their transform hint.
2314 //
2315 // If a layer is visible only on a single display, then that
2316 // display is used to calculate the hint, otherwise we use the
2317 // default display.
2318 //
2319 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2320 // the hint is set before we acquire a buffer from the surface texture.
2321 //
2322 // NOTE: layer transactions have taken place already, so we use their
2323 // drawing state. However, SurfaceFlinger's own transaction has not
2324 // happened yet, so we must use the current state layer list
2325 // (soon to become the drawing state list).
2326 //
2327 sp<const DisplayDevice> disp;
2328 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002329 bool first = true;
2330 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002331 // NOTE: we rely on the fact that layers are sorted by
2332 // layerStack first (so we don't have to traverse the list
2333 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002334 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002335 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002336 currentlayerStack = layerStack;
2337 // figure out if this layerstack is mirrored
2338 // (more than one display) if so, pick the default display,
2339 // if not, pick the only display it's on.
2340 disp.clear();
2341 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2342 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002343 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002344 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002345 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002346 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002347 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002348 break;
2349 }
2350 }
2351 }
2352 }
Chet Haase91d25932013-04-11 15:24:55 -07002353 if (disp == NULL) {
2354 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2355 // redraw after transform hint changes. See bug 8508397.
2356
2357 // could be null when this layer is using a layerStack
2358 // that is not visible on any display. Also can occur at
2359 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002360 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002361 }
Chet Haase91d25932013-04-11 15:24:55 -07002362 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002363
2364 first = false;
2365 });
Mathias Agopian84300952012-11-21 16:02:13 -08002366 }
2367
2368
Mathias Agopian3559b072012-08-15 13:46:03 -07002369 /*
2370 * Perform our own transaction if needed
2371 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002372
2373 if (mLayersAdded) {
2374 mLayersAdded = false;
2375 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002376 mVisibleRegionsDirty = true;
2377 }
2378
2379 // some layers might have been removed, so
2380 // we need to update the regions they're exposing.
2381 if (mLayersRemoved) {
2382 mLayersRemoved = false;
2383 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002384 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002385 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002386 // this layer is not visible anymore
2387 // TODO: we could traverse the tree from front to back and
2388 // compute the actual visible region
2389 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002390 Region visibleReg;
2391 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002392 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002393 }
Robert Carr2047fae2016-11-28 14:09:09 -08002394 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002395 }
2396
2397 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002398
2399 updateCursorAsync();
2400}
2401
2402void SurfaceFlinger::updateCursorAsync()
2403{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002404 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2405 auto& displayDevice = mDisplays[displayId];
2406 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002407 continue;
2408 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002409
2410 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2411 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002412 }
2413 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002414}
2415
2416void SurfaceFlinger::commitTransaction()
2417{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002418 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002419 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002420 for (const auto& l : mLayersPendingRemoval) {
2421 recordBufferingStats(l->getName().string(),
2422 l->getOccupancyHistory(true));
2423 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002424 }
2425 mLayersPendingRemoval.clear();
2426 }
2427
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002428 // If this transaction is part of a window animation then the next frame
2429 // we composite should be considered an animation as well.
2430 mAnimCompositionPending = mAnimTransactionPending;
2431
Mathias Agopian4fec8732012-06-29 14:12:52 -07002432 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002433 mDrawingState.traverseInZOrder([](Layer* layer) {
2434 layer->commitChildList();
2435 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002436 mTransactionPending = false;
2437 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002438 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439}
2440
Chia-I Wuab0c3192017-08-01 11:29:00 -07002441void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002442 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002443{
Mathias Agopian841cde52012-03-01 15:44:37 -08002444 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002445 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002446
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002447 Region aboveOpaqueLayers;
2448 Region aboveCoveredLayers;
2449 Region dirty;
2450
Mathias Agopian87baae12012-07-31 12:38:26 -07002451 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452
Robert Carr2047fae2016-11-28 14:09:09 -08002453 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002455 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456
Jesse Hall01e29052013-02-19 16:13:35 -08002457 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002458 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002459 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002460
Mathias Agopianab028732010-03-16 16:41:46 -07002461 /*
2462 * opaqueRegion: area of a surface that is fully opaque.
2463 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002464 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002465
2466 /*
2467 * visibleRegion: area of a surface that is visible on screen
2468 * and not fully transparent. This is essentially the layer's
2469 * footprint minus the opaque regions above it.
2470 * Areas covered by a translucent surface are considered visible.
2471 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002472 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002473
2474 /*
2475 * coveredRegion: area of a surface that is covered by all
2476 * visible regions above it (which includes the translucent areas).
2477 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002478 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002479
Jesse Halla8026d22012-09-25 13:25:04 -07002480 /*
2481 * transparentRegion: area of a surface that is hinted to be completely
2482 * transparent. This is only used to tell when the layer has no visible
2483 * non-transparent regions and can be removed from the layer list. It
2484 * does not affect the visibleRegion of this layer or any layers
2485 * beneath it. The hint may not be correct if apps don't respect the
2486 * SurfaceView restrictions (which, sadly, some don't).
2487 */
2488 Region transparentRegion;
2489
Mathias Agopianab028732010-03-16 16:41:46 -07002490
2491 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002492 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002493 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002494 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002496 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002497 if (!visibleRegion.isEmpty()) {
2498 // Remove the transparent area from the visible region
2499 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002500 if (tr.preserveRects()) {
2501 // transform the transparent region
2502 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002503 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002504 // transformation too complex, can't do the
2505 // transparent region optimization.
2506 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002507 }
Mathias Agopianab028732010-03-16 16:41:46 -07002508 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509
Mathias Agopianab028732010-03-16 16:41:46 -07002510 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002511 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002512 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002513 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2514 // the opaque region is the layer's footprint
2515 opaqueRegion = visibleRegion;
2516 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517 }
2518 }
2519
Mathias Agopianab028732010-03-16 16:41:46 -07002520 // Clip the covered region to the visible region
2521 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2522
2523 // Update aboveCoveredLayers for next (lower) layer
2524 aboveCoveredLayers.orSelf(visibleRegion);
2525
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526 // subtract the opaque region covered by the layers above us
2527 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002528
2529 // compute this layer's dirty region
2530 if (layer->contentDirty) {
2531 // we need to invalidate the whole region
2532 dirty = visibleRegion;
2533 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002534 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002535 layer->contentDirty = false;
2536 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002537 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002538 * the exposed region consists of two components:
2539 * 1) what's VISIBLE now and was COVERED before
2540 * 2) what's EXPOSED now less what was EXPOSED before
2541 *
2542 * note that (1) is conservative, we start with the whole
2543 * visible region but only keep what used to be covered by
2544 * something -- which mean it may have been exposed.
2545 *
2546 * (2) handles areas that were not covered by anything but got
2547 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002548 */
Mathias Agopianab028732010-03-16 16:41:46 -07002549 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002550 const Region oldVisibleRegion = layer->visibleRegion;
2551 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002552 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2553 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554 }
2555 dirty.subtractSelf(aboveOpaqueLayers);
2556
2557 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002558 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559
Mathias Agopianab028732010-03-16 16:41:46 -07002560 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002562
Jesse Halla8026d22012-09-25 13:25:04 -07002563 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564 layer->setVisibleRegion(visibleRegion);
2565 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002566 layer->setVisibleNonTransparentRegion(
2567 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002568 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569
Mathias Agopian87baae12012-07-31 12:38:26 -07002570 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571}
2572
Chia-I Wuab0c3192017-08-01 11:29:00 -07002573void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002574 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002575 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002576 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002577 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002578 }
2579 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002580}
2581
Dan Stoza6b9454d2014-11-07 16:00:59 -08002582bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002584 ALOGV("handlePageFlip");
2585
Brian Andersond6927fb2016-07-23 23:37:30 -07002586 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587
Mathias Agopian4fec8732012-06-29 14:12:52 -07002588 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002589 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002590 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002591
2592 // Store the set of layers that need updates. This set must not change as
2593 // buffers are being latched, as this could result in a deadlock.
2594 // Example: Two producers share the same command stream and:
2595 // 1.) Layer 0 is latched
2596 // 2.) Layer 0 gets a new frame
2597 // 2.) Layer 1 gets a new frame
2598 // 3.) Layer 1 is latched.
2599 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2600 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002601 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002602 if (layer->hasQueuedFrame()) {
2603 frameQueued = true;
2604 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002605 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002606 } else {
2607 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002608 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002609 } else {
2610 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002611 }
Robert Carr2047fae2016-11-28 14:09:09 -08002612 });
2613
Dan Stoza9e56aa02015-11-02 13:00:03 -08002614 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002615 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002616 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002617 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002618 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002619 newDataLatched = true;
2620 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002621 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002622
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002623 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002624
2625 // If we will need to wake up at some time in the future to deal with a
2626 // queued frame that shouldn't be displayed during this vsync period, wake
2627 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002628 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002629 signalLayerUpdate();
2630 }
2631
2632 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002633 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634}
2635
Mathias Agopianad456f92011-01-13 17:53:01 -08002636void SurfaceFlinger::invalidateHwcGeometry()
2637{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002638 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002639}
2640
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002641
Fabien Sanglard830b8472016-11-30 16:35:58 -08002642void SurfaceFlinger::doDisplayComposition(
2643 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002644 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645{
Dan Stoza71433162014-02-04 16:22:36 -08002646 // We only need to actually compose the display if:
2647 // 1) It is being handled by hardware composer, which may need this to
2648 // keep its virtual display state machine in sync, or
2649 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002650 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002651 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002652 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002653 return;
2654 }
2655
Dan Stoza9e56aa02015-11-02 13:00:03 -08002656 ALOGV("doDisplayComposition");
2657
Mathias Agopian87baae12012-07-31 12:38:26 -07002658 Region dirtyRegion(inDirtyRegion);
2659
Mathias Agopianb8a55602009-06-26 19:06:36 -07002660 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002661 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662
Fabien Sanglard830b8472016-11-30 16:35:58 -08002663 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002664 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002665 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2666 // takes a rectangle, we must make sure to update that whole
2667 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002668 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002669 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002670 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002671 // We need to redraw the rectangle that will be updated
2672 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002673 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002674 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002675 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002676 } else {
2677 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002678 dirtyRegion.set(displayDevice->bounds());
2679 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680 }
2681 }
2682
Fabien Sanglard830b8472016-11-30 16:35:58 -08002683 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002684
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002685 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002686 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002687
2688 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002689 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690}
2691
Dan Stoza9e56aa02015-11-02 13:00:03 -08002692bool SurfaceFlinger::doComposeSurfaces(
2693 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002694{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002695 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002696
chaviwa76b2712017-09-20 12:02:26 -07002697 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002698 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002699
2700 mat4 oldColorMatrix;
2701 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2702 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2703 if (applyColorMatrix) {
2704 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2705 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2706 }
2707
Dan Stoza9e56aa02015-11-02 13:00:03 -08002708 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2709 if (hasClientComposition) {
2710 ALOGV("hasClientComposition");
2711
Romain Guy54f154a2017-10-24 21:40:32 +01002712 mRenderEngine->setWideColor(
2713 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2714 mRenderEngine->setColorMode(mForceNativeColorMode ?
2715 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002716 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002717 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002718 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002719 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002720
2721 // |mStateLock| not needed as we are on the main thread
2722 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002723 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2724 }
2725 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002726 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002727
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002728 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002729 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2730 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002731 // when using overlays, we assume a fully transparent framebuffer
2732 // NOTE: we could reduce how much we need to clear, for instance
2733 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002734 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002735 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002736 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002737 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002738 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002739 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002740
2741 // we remove the scissor part
2742 // we're left with the letterbox region
2743 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002744 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002745
2746 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002747 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002748
2749 // but limit it to the dirty region
2750 region.andSelf(dirty);
2751
Mathias Agopianb9494d52012-04-18 02:28:45 -07002752 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002753 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002754 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002755 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002756 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002757 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002758
Dan Stoza9e56aa02015-11-02 13:00:03 -08002759 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002760 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002761 // scissor on the main display. It should never be needed
2762 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002763 const Rect& bounds(displayDevice->getBounds());
2764 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002765 if (scissor != bounds) {
2766 // scissor doesn't match the screen's dimensions, so we
2767 // need to clear everything outside of it and enable
2768 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002769
Mathias Agopianf45c5102012-10-24 16:29:17 -07002770 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 const uint32_t height = displayDevice->getHeight();
2772 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002773 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002774 }
2775 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002776 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002777
Mathias Agopian85d751c2012-08-29 16:59:24 -07002778 /*
2779 * and then, render the layers targeted at the framebuffer
2780 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002781
Dan Stoza9e56aa02015-11-02 13:00:03 -08002782 ALOGV("Rendering client layers");
2783 const Transform& displayTransform = displayDevice->getTransform();
2784 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002785 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002786 bool firstLayer = true;
2787 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2788 const Region clip(dirty.intersect(
2789 displayTransform.transform(layer->visibleRegion)));
2790 ALOGV("Layer: %s", layer->getName().string());
2791 ALOGV(" Composition type: %s",
2792 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002793 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002794 switch (layer->getCompositionType(hwcId)) {
2795 case HWC2::Composition::Cursor:
2796 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002797 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002798 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002799 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002800 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002801 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002802 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002803 // never clear the very first layer since we're
2804 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002805 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002806 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002807 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002808 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002809 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002810 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002811 break;
2812 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002813 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002814 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002815 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002816 } else {
2817 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002818 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002819 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002820 }
2821 } else {
2822 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002823 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002824 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002825 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002826 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002827 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002828 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002829 }
2830 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002831
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002832 if (applyColorMatrix) {
2833 getRenderEngine().setupColorTransform(oldColorMatrix);
2834 }
2835
Mathias Agopianf45c5102012-10-24 16:29:17 -07002836 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002837 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002838 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839}
2840
Fabien Sanglard830b8472016-11-30 16:35:58 -08002841void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2842 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002843 RenderEngine& engine(getRenderEngine());
2844 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845}
2846
Dan Stoza7d89d062015-04-30 13:29:25 -07002847status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002848 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002849 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002850 const sp<Layer>& lbc,
2851 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002852{
Dan Stoza7d89d062015-04-30 13:29:25 -07002853 // add this layer to the current state list
2854 {
2855 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002856 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002857 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2858 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002859 return NO_MEMORY;
2860 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002861 if (parent == nullptr) {
2862 mCurrentState.layersSortedByZ.add(lbc);
2863 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002864 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002865 ALOGE("addClientLayer called with a removed parent");
2866 return NAME_NOT_FOUND;
2867 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002868 parent->addChild(lbc);
2869 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002870
Dan Stoza7d89d062015-04-30 13:29:25 -07002871 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002872 mLayersAdded = true;
2873 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002874 }
2875
Mathias Agopian96f08192010-06-02 23:28:45 -07002876 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002877 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002878
Dan Stoza7d89d062015-04-30 13:29:25 -07002879 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002880}
2881
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002882status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002883 Mutex::Autolock _l(mStateLock);
2884
chaviw8b3871a2017-11-01 17:41:01 -07002885 if (layer->isPendingRemoval()) {
2886 return NO_ERROR;
2887 }
2888
Robert Carr1f0a16a2016-10-24 16:27:39 -07002889 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002890 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002891 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002892 if (topLevelOnly) {
2893 return NO_ERROR;
2894 }
2895
Chia-I Wu98f1c102017-05-30 14:54:08 -07002896 sp<Layer> ancestor = p;
2897 while (ancestor->getParent() != nullptr) {
2898 ancestor = ancestor->getParent();
2899 }
2900 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2901 ALOGE("removeLayer called with a layer whose parent has been removed");
2902 return NAME_NOT_FOUND;
2903 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002904
2905 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002906 } else {
2907 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002908 }
2909
Robert Carr136e2f62017-02-08 17:54:29 -08002910 // As a matter of normal operation, the LayerCleaner will produce a second
2911 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2912 // so we will succeed in promoting it, but it's already been removed
2913 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2914 // otherwise something has gone wrong and we are leaking the layer.
2915 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002916 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2917 layer->getName().string(),
2918 (p != nullptr) ? p->getName().string() : "no-parent");
2919 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002920 } else if (index < 0) {
2921 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002922 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002923
Chia-I Wuc6657022017-08-15 11:18:17 -07002924 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002925 mLayersPendingRemoval.add(layer);
2926 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002927 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002928 setTransactionFlags(eTransactionNeeded);
2929 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930}
2931
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002932uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002933 return android_atomic_release_load(&mTransactionFlags);
2934}
2935
Mathias Agopian3f844832013-08-07 21:24:32 -07002936uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2938}
2939
Mathias Agopian3f844832013-08-07 21:24:32 -07002940uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002941 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2942 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002943 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002944 }
2945 return old;
2946}
2947
Mathias Agopian8b33f032012-07-24 20:43:54 -07002948void SurfaceFlinger::setTransactionState(
2949 const Vector<ComposerState>& state,
2950 const Vector<DisplayState>& displays,
2951 uint32_t flags)
2952{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002953 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002954 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002955 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002956
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002957 if (flags & eAnimation) {
2958 // For window updates that are part of an animation we must wait for
2959 // previous animation "frames" to be handled.
2960 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002961 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002962 if (CC_UNLIKELY(err != NO_ERROR)) {
2963 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002964 // caller after a few seconds.
2965 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2966 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002967 mAnimTransactionPending = false;
2968 break;
2969 }
2970 }
2971 }
2972
Mathias Agopiane57f2922012-08-09 16:29:12 -07002973 size_t count = displays.size();
2974 for (size_t i=0 ; i<count ; i++) {
2975 const DisplayState& s(displays[i]);
2976 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002977 }
2978
Mathias Agopiane57f2922012-08-09 16:29:12 -07002979 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002980 for (size_t i=0 ; i<count ; i++) {
2981 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002982 // Here we need to check that the interface we're given is indeed
2983 // one of our own. A malicious client could give us a NULL
2984 // IInterface, or one of its own or even one of our own but a
2985 // different type. All these situations would cause us to crash.
2986 //
2987 // NOTE: it would be better to use RTTI as we could directly check
2988 // that we have a Client*. however, RTTI is disabled in Android.
2989 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002990 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002991 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002992 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002993 sp<Client> client( static_cast<Client *>(s.client.get()) );
2994 transactionFlags |= setClientStateLocked(client, s.state);
2995 }
2996 }
2997 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002998 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002999
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003000 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3001 // anyway. This can be used as a flush mechanism for previous async transactions.
3002 // Empty animation transaction can be used to simulate back-pressure, so also force a
3003 // transaction for empty animation transactions.
3004 if (transactionFlags == 0 &&
3005 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003006 transactionFlags = eTransactionNeeded;
3007 }
3008
Mathias Agopian386aa982011-11-07 21:58:03 -08003009 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003010 if (mInterceptor.isEnabled()) {
3011 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
3012 }
Irvel468051e2016-06-13 16:44:44 -07003013
Mathias Agopian386aa982011-11-07 21:58:03 -08003014 // this triggers the transaction
3015 setTransactionFlags(transactionFlags);
3016
3017 // if this is a synchronous transaction, wait for it to take effect
3018 // before returning.
3019 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003020 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003021 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003022 if (flags & eAnimation) {
3023 mAnimTransactionPending = true;
3024 }
3025 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003026 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3027 if (CC_UNLIKELY(err != NO_ERROR)) {
3028 // just in case something goes wrong in SF, return to the
3029 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003030 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3031 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003032 break;
3033 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003034 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003035 }
3036}
3037
Mathias Agopiane57f2922012-08-09 16:29:12 -07003038uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3039{
Jesse Hall9a143922012-10-04 16:29:19 -07003040 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3041 if (dpyIdx < 0)
3042 return 0;
3043
Mathias Agopiane57f2922012-08-09 16:29:12 -07003044 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003045 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003046 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003047 const uint32_t what = s.what;
3048 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003049 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003050 disp.surface = s.surface;
3051 flags |= eDisplayTransactionNeeded;
3052 }
3053 }
3054 if (what & DisplayState::eLayerStackChanged) {
3055 if (disp.layerStack != s.layerStack) {
3056 disp.layerStack = s.layerStack;
3057 flags |= eDisplayTransactionNeeded;
3058 }
3059 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003060 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003061 if (disp.orientation != s.orientation) {
3062 disp.orientation = s.orientation;
3063 flags |= eDisplayTransactionNeeded;
3064 }
3065 if (disp.frame != s.frame) {
3066 disp.frame = s.frame;
3067 flags |= eDisplayTransactionNeeded;
3068 }
3069 if (disp.viewport != s.viewport) {
3070 disp.viewport = s.viewport;
3071 flags |= eDisplayTransactionNeeded;
3072 }
3073 }
Michael Lentine47e45402014-07-18 15:34:25 -07003074 if (what & DisplayState::eDisplaySizeChanged) {
3075 if (disp.width != s.width) {
3076 disp.width = s.width;
3077 flags |= eDisplayTransactionNeeded;
3078 }
3079 if (disp.height != s.height) {
3080 disp.height = s.height;
3081 flags |= eDisplayTransactionNeeded;
3082 }
3083 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003084 }
3085 return flags;
3086}
3087
3088uint32_t SurfaceFlinger::setClientStateLocked(
3089 const sp<Client>& client,
3090 const layer_state_t& s)
3091{
Mathias Agopian13127d82013-03-05 17:47:11 -08003092 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003093 if (layer == nullptr) {
3094 return 0;
3095 }
3096
3097 if (layer->isPendingRemoval()) {
3098 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3099 return 0;
3100 }
3101
3102 uint32_t flags = 0;
3103
3104 const uint32_t what = s.what;
3105 bool geometryAppliesWithResize =
3106 what & layer_state_t::eGeometryAppliesWithResize;
3107 if (what & layer_state_t::ePositionChanged) {
3108 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3109 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003110 }
chaviw8b3871a2017-11-01 17:41:01 -07003111 }
3112 if (what & layer_state_t::eLayerChanged) {
3113 // NOTE: index needs to be calculated before we update the state
3114 const auto& p = layer->getParent();
3115 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003116 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003117 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003118 mCurrentState.layersSortedByZ.removeAt(idx);
3119 mCurrentState.layersSortedByZ.add(layer);
3120 // we need traversal (state changed)
3121 // AND transaction (list changed)
3122 flags |= eTransactionNeeded|eTraversalNeeded;
3123 }
chaviw8b3871a2017-11-01 17:41:01 -07003124 } else {
3125 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003126 flags |= eTransactionNeeded|eTraversalNeeded;
3127 }
3128 }
chaviw8b3871a2017-11-01 17:41:01 -07003129 }
3130 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003131 // NOTE: index needs to be calculated before we update the state
3132 const auto& p = layer->getParent();
3133 if (p == nullptr) {
3134 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3135 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3136 mCurrentState.layersSortedByZ.removeAt(idx);
3137 mCurrentState.layersSortedByZ.add(layer);
3138 // we need traversal (state changed)
3139 // AND transaction (list changed)
3140 flags |= eTransactionNeeded|eTraversalNeeded;
3141 }
3142 } else {
3143 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3144 flags |= eTransactionNeeded|eTraversalNeeded;
3145 }
chaviw8b3871a2017-11-01 17:41:01 -07003146 }
3147 }
3148 if (what & layer_state_t::eSizeChanged) {
3149 if (layer->setSize(s.w, s.h)) {
3150 flags |= eTraversalNeeded;
3151 }
3152 }
3153 if (what & layer_state_t::eAlphaChanged) {
3154 if (layer->setAlpha(s.alpha))
3155 flags |= eTraversalNeeded;
3156 }
3157 if (what & layer_state_t::eColorChanged) {
3158 if (layer->setColor(s.color))
3159 flags |= eTraversalNeeded;
3160 }
3161 if (what & layer_state_t::eMatrixChanged) {
3162 if (layer->setMatrix(s.matrix))
3163 flags |= eTraversalNeeded;
3164 }
3165 if (what & layer_state_t::eTransparentRegionChanged) {
3166 if (layer->setTransparentRegionHint(s.transparentRegion))
3167 flags |= eTraversalNeeded;
3168 }
3169 if (what & layer_state_t::eFlagsChanged) {
3170 if (layer->setFlags(s.flags, s.mask))
3171 flags |= eTraversalNeeded;
3172 }
3173 if (what & layer_state_t::eCropChanged) {
3174 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3175 flags |= eTraversalNeeded;
3176 }
3177 if (what & layer_state_t::eFinalCropChanged) {
3178 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3179 flags |= eTraversalNeeded;
3180 }
3181 if (what & layer_state_t::eLayerStackChanged) {
3182 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3183 // We only allow setting layer stacks for top level layers,
3184 // everything else inherits layer stack from its parent.
3185 if (layer->hasParent()) {
3186 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3187 layer->getName().string());
3188 } else if (idx < 0) {
3189 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3190 "that also does not appear in the top level layer list. Something"
3191 " has gone wrong.", layer->getName().string());
3192 } else if (layer->setLayerStack(s.layerStack)) {
3193 mCurrentState.layersSortedByZ.removeAt(idx);
3194 mCurrentState.layersSortedByZ.add(layer);
3195 // we need traversal (state changed)
3196 // AND transaction (list changed)
3197 flags |= eTransactionNeeded|eTraversalNeeded;
3198 }
3199 }
3200 if (what & layer_state_t::eDeferTransaction) {
3201 if (s.barrierHandle != nullptr) {
3202 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3203 } else if (s.barrierGbp != nullptr) {
3204 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3205 if (authenticateSurfaceTextureLocked(gbp)) {
3206 const auto& otherLayer =
3207 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3208 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3209 } else {
3210 ALOGE("Attempt to defer transaction to to an"
3211 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003212 }
3213 }
chaviw8b3871a2017-11-01 17:41:01 -07003214 // We don't trigger a traversal here because if no other state is
3215 // changed, we don't want this to cause any more work
3216 }
3217 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003218 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003219 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003220 if (!hadParent) {
3221 mCurrentState.layersSortedByZ.remove(layer);
3222 }
chaviw8b3871a2017-11-01 17:41:01 -07003223 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003224 }
chaviw8b3871a2017-11-01 17:41:01 -07003225 }
3226 if (what & layer_state_t::eReparentChildren) {
3227 if (layer->reparentChildren(s.reparentHandle)) {
3228 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003229 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003230 }
chaviw8b3871a2017-11-01 17:41:01 -07003231 if (what & layer_state_t::eDetachChildren) {
3232 layer->detachChildren();
3233 }
3234 if (what & layer_state_t::eOverrideScalingModeChanged) {
3235 layer->setOverrideScalingMode(s.overrideScalingMode);
3236 // We don't trigger a traversal here because if no other state is
3237 // changed, we don't want this to cause any more work
3238 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003239 return flags;
3240}
3241
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003242status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003243 const String8& name,
3244 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003245 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003246 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3247 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003249 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003250 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003251 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003252 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003253 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003254
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003255 status_t result = NO_ERROR;
3256
3257 sp<Layer> layer;
3258
Cody Northropbc755282017-03-31 12:00:08 -06003259 String8 uniqueName = getUniqueLayerName(name);
3260
Mathias Agopian3165cc22012-08-08 19:42:09 -07003261 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3262 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003263 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003264 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003265 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003266
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267 break;
chaviw13fdc492017-06-27 12:40:18 -07003268 case ISurfaceComposerClient::eFXSurfaceColor:
3269 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003270 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003271 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003272 break;
3273 default:
3274 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003275 break;
3276 }
3277
Dan Stoza7d89d062015-04-30 13:29:25 -07003278 if (result != NO_ERROR) {
3279 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003280 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003281
Chia-I Wuab0c3192017-08-01 11:29:00 -07003282 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3283 // TODO b/64227542
3284 if (windowType == 441731) {
3285 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3286 layer->setPrimaryDisplayOnly();
3287 }
3288
Albert Chaulk479c60c2017-01-27 14:21:34 -05003289 layer->setInfo(windowType, ownerUid);
3290
Robert Carr1f0a16a2016-10-24 16:27:39 -07003291 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003292 if (result != NO_ERROR) {
3293 return result;
3294 }
Irvelffc9efc2016-07-27 15:16:37 -07003295 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003296
3297 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003298 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003299}
3300
Cody Northropbc755282017-03-31 12:00:08 -06003301String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3302{
3303 bool matchFound = true;
3304 uint32_t dupeCounter = 0;
3305
3306 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3307 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3308
3309 // Loop over layers until we're sure there is no matching name
3310 while (matchFound) {
3311 matchFound = false;
3312 mDrawingState.traverseInZOrder([&](Layer* layer) {
3313 if (layer->getName() == uniqueName) {
3314 matchFound = true;
3315 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3316 }
3317 });
3318 }
3319
3320 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3321
3322 return uniqueName;
3323}
3324
David Sodman0c69cad2017-08-21 12:12:51 -07003325status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003326 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3327 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003328{
3329 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003330 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003331 case PIXEL_FORMAT_TRANSPARENT:
3332 case PIXEL_FORMAT_TRANSLUCENT:
3333 format = PIXEL_FORMAT_RGBA_8888;
3334 break;
3335 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003336 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003337 break;
3338 }
3339
David Sodman0c69cad2017-08-21 12:12:51 -07003340 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3341 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003342 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003343 *handle = layer->getHandle();
3344 *gbp = layer->getProducer();
3345 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003346 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003347
David Sodman0c69cad2017-08-21 12:12:51 -07003348 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003349 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003350}
3351
chaviw13fdc492017-06-27 12:40:18 -07003352status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003353 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003354 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003355{
chaviw13fdc492017-06-27 12:40:18 -07003356 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003357 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003358 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003359}
3360
Mathias Agopianac9fa422013-02-11 16:40:36 -08003361status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003362{
Robert Carr9524cb32017-02-13 11:32:32 -08003363 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003364 status_t err = NO_ERROR;
3365 sp<Layer> l(client->getLayerUser(handle));
3366 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003367 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003368 err = removeLayer(l);
3369 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3370 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003371 }
3372 return err;
3373}
3374
Mathias Agopian13127d82013-03-05 17:47:11 -08003375status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003376{
Mathias Agopian67106042013-03-14 19:18:13 -07003377 // called by ~LayerCleaner() when all references to the IBinder (handle)
3378 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003379 sp<Layer> l = layer.promote();
3380 if (l == nullptr) {
3381 // The layer has already been removed, carry on
3382 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003383 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003384 // If we have a parent, then we can continue to live as long as it does.
3385 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003386}
3387
Mathias Agopianb60314a2012-04-10 22:09:54 -07003388// ---------------------------------------------------------------------------
3389
Andy McFadden13a082e2012-08-24 10:16:42 -07003390void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003391 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003392 Vector<ComposerState> state;
3393 Vector<DisplayState> displays;
3394 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003395 d.what = DisplayState::eDisplayProjectionChanged |
3396 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003397 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003398 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003399 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003400 d.frame.makeInvalid();
3401 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003402 d.width = 0;
3403 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003404 displays.add(d);
3405 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003406 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3407 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003408
Dan Stoza9e56aa02015-11-02 13:00:03 -08003409 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3410 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003411 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003412
Brian Andersond0010582017-03-07 13:20:31 -08003413 // Use phase of 0 since phase is not known.
3414 // Use latency of 0, which will snap to the ideal latency.
3415 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003416}
3417
3418void SurfaceFlinger::initializeDisplays() {
3419 class MessageScreenInitialized : public MessageBase {
3420 SurfaceFlinger* flinger;
3421 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003422 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003423 virtual bool handler() {
3424 flinger->onInitializeDisplays();
3425 return true;
3426 }
3427 };
3428 sp<MessageBase> msg = new MessageScreenInitialized(this);
3429 postMessageAsync(msg); // we may be called from main thread, use async message
3430}
3431
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003432void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003433 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003434 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3435 this);
3436 int32_t type = hw->getDisplayType();
3437 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003438
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003439 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003440 return;
3441 }
3442
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003443 hw->setPowerMode(mode);
3444 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3445 ALOGW("Trying to set power mode for virtual display");
3446 return;
3447 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003448
Irvelffc9efc2016-07-27 15:16:37 -07003449 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003450 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003451 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3452 if (idx < 0) {
3453 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3454 return;
3455 }
3456 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3457 }
3458
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003459 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003460 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003461 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003462 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3463 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003464 // FIXME: eventthread only knows about the main display right now
3465 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003466 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003467 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003468
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003469 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003470 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003471 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003472
3473 struct sched_param param = {0};
3474 param.sched_priority = 1;
3475 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3476 ALOGW("Couldn't set SCHED_FIFO on display on");
3477 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003478 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003479 // Turn off the display
3480 struct sched_param param = {0};
3481 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3482 ALOGW("Couldn't set SCHED_OTHER on display off");
3483 }
3484
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003485 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3486 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003487 disableHardwareVsync(true); // also cancels any in-progress resync
3488
Mathias Agopiancde87a32012-09-13 14:09:01 -07003489 // FIXME: eventthread only knows about the main display right now
3490 mEventThread->onScreenReleased();
3491 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003492
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003493 getHwComposer().setPowerMode(type, mode);
3494 mVisibleRegionsDirty = true;
3495 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003496 } else if (mode == HWC_POWER_MODE_DOZE ||
3497 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003498 // Update display while dozing
3499 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003500 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3501 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003502 // FIXME: eventthread only knows about the main display right now
3503 mEventThread->onScreenAcquired();
3504 resyncToHardwareVsync(true);
3505 }
3506 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3507 // Leave display going to doze
3508 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3509 disableHardwareVsync(true); // also cancels any in-progress resync
3510 // FIXME: eventthread only knows about the main display right now
3511 mEventThread->onScreenReleased();
3512 }
3513 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003514 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003515 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003516 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003517 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003518}
3519
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003520void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3521 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003522 SurfaceFlinger& mFlinger;
3523 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003524 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003525 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003526 MessageSetPowerMode(SurfaceFlinger& flinger,
3527 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3528 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003529 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003530 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003531 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003532 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003533 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003534 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003535 ALOGW("Attempt to set power mode = %d for virtual display",
3536 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003537 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003538 mFlinger.setPowerModeInternal(
3539 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003540 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003541 return true;
3542 }
3543 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003544 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003545 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003546}
3547
3548// ---------------------------------------------------------------------------
3549
Vishnu Nair6a408532017-10-24 09:11:27 -07003550status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003551 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003552
Mathias Agopianbd115332013-04-18 16:41:04 -07003553 IPCThreadState* ipc = IPCThreadState::self();
3554 const int pid = ipc->getCallingPid();
3555 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003556
Mathias Agopianbd115332013-04-18 16:41:04 -07003557 if ((uid != AID_SHELL) &&
3558 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003559 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003560 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003561 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003562 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003563 // (this would indicate SF is stuck, but we want to be able to
3564 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003565 status_t err = mStateLock.timedLock(s2ns(1));
3566 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003567 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003568 result.appendFormat(
3569 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3570 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003571 }
3572
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003573 bool dumpAll = true;
3574 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003575 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003576
3577 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003578 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003579 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3580 dumpAll = false;
3581 }
3582
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003583 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003584 if ((index < numArgs) &&
3585 (args[index] == String16("--list"))) {
3586 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003587 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003588 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003589 }
3590
3591 if ((index < numArgs) &&
3592 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003593 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003594 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003595 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003596 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003597
3598 if ((index < numArgs) &&
3599 (args[index] == String16("--latency-clear"))) {
3600 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003601 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003602 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003603 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003604
3605 if ((index < numArgs) &&
3606 (args[index] == String16("--dispsync"))) {
3607 index++;
3608 mPrimaryDispSync.dump(result);
3609 dumpAll = false;
3610 }
Dan Stozab90cf072015-03-05 11:05:59 -08003611
3612 if ((index < numArgs) &&
3613 (args[index] == String16("--static-screen"))) {
3614 index++;
3615 dumpStaticScreenStats(result);
3616 dumpAll = false;
3617 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003618
3619 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003620 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003621 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003622 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003623 dumpAll = false;
3624 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003625
3626 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3627 index++;
3628 dumpWideColorInfo(result);
3629 dumpAll = false;
3630 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003632
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003633 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003634 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003635 }
3636
Mathias Agopian9795c422009-08-26 16:36:26 -07003637 if (locked) {
3638 mStateLock.unlock();
3639 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003640 }
3641 write(fd, result.string(), result.size());
3642 return NO_ERROR;
3643}
3644
Dan Stozac7014012014-02-14 15:03:43 -08003645void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3646 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003647{
Robert Carr2047fae2016-11-28 14:09:09 -08003648 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003649 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003650 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003651}
3652
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003653void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003654 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003655{
3656 String8 name;
3657 if (index < args.size()) {
3658 name = String8(args[index]);
3659 index++;
3660 }
3661
Dan Stoza9e56aa02015-11-02 13:00:03 -08003662 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3663 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003664 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003665
3666 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003667 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003668 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003669 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003670 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003671 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003672 }
Robert Carr2047fae2016-11-28 14:09:09 -08003673 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003674 }
3675}
3676
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003677void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003678 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003679{
3680 String8 name;
3681 if (index < args.size()) {
3682 name = String8(args[index]);
3683 index++;
3684 }
3685
Robert Carr2047fae2016-11-28 14:09:09 -08003686 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003687 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003688 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003689 }
Robert Carr2047fae2016-11-28 14:09:09 -08003690 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003691
Svetoslavd85084b2014-03-20 10:28:31 -07003692 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003693}
3694
Jamie Gennis6547ff42013-07-16 20:12:42 -07003695// This should only be called from the main thread. Otherwise it would need
3696// the lock and should use mCurrentState rather than mDrawingState.
3697void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003698 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003699 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003700 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003701
3702 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3703}
3704
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003705void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003706{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003707 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003708 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3709
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003710 if (isLayerTripleBufferingDisabled())
3711 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003712
3713 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003714 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003715 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003716 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003717 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3718 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003719 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003720}
3721
Dan Stozab90cf072015-03-05 11:05:59 -08003722void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3723{
3724 result.appendFormat("Static screen stats:\n");
3725 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3726 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3727 float percent = 100.0f *
3728 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3729 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3730 b + 1, bucketTimeSec, percent);
3731 }
3732 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3733 float percent = 100.0f *
3734 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3735 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3736 NUM_BUCKETS - 1, bucketTimeSec, percent);
3737}
3738
Dan Stozae77c7662016-05-13 11:37:28 -07003739void SurfaceFlinger::recordBufferingStats(const char* layerName,
3740 std::vector<OccupancyTracker::Segment>&& history) {
3741 Mutex::Autolock lock(mBufferingStatsMutex);
3742 auto& stats = mBufferingStats[layerName];
3743 for (const auto& segment : history) {
3744 if (!segment.usedThirdBuffer) {
3745 stats.twoBufferTime += segment.totalTime;
3746 }
3747 if (segment.occupancyAverage < 1.0f) {
3748 stats.doubleBufferedTime += segment.totalTime;
3749 } else if (segment.occupancyAverage < 2.0f) {
3750 stats.tripleBufferedTime += segment.totalTime;
3751 }
3752 ++stats.numSegments;
3753 stats.totalTime += segment.totalTime;
3754 }
3755}
3756
Brian Andersond6927fb2016-07-23 23:37:30 -07003757void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3758 result.appendFormat("Layer frame timestamps:\n");
3759
3760 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3761 const size_t count = currentLayers.size();
3762 for (size_t i=0 ; i<count ; i++) {
3763 currentLayers[i]->dumpFrameEvents(result);
3764 }
3765}
3766
Dan Stozae77c7662016-05-13 11:37:28 -07003767void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3768 result.append("Buffering stats:\n");
3769 result.append(" [Layer name] <Active time> <Two buffer> "
3770 "<Double buffered> <Triple buffered>\n");
3771 Mutex::Autolock lock(mBufferingStatsMutex);
3772 typedef std::tuple<std::string, float, float, float> BufferTuple;
3773 std::map<float, BufferTuple, std::greater<float>> sorted;
3774 for (const auto& statsPair : mBufferingStats) {
3775 const char* name = statsPair.first.c_str();
3776 const BufferingStats& stats = statsPair.second;
3777 if (stats.numSegments == 0) {
3778 continue;
3779 }
3780 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3781 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3782 stats.totalTime;
3783 float doubleBufferRatio = static_cast<float>(
3784 stats.doubleBufferedTime) / stats.totalTime;
3785 float tripleBufferRatio = static_cast<float>(
3786 stats.tripleBufferedTime) / stats.totalTime;
3787 sorted.insert({activeTime, {name, twoBufferRatio,
3788 doubleBufferRatio, tripleBufferRatio}});
3789 }
3790 for (const auto& sortedPair : sorted) {
3791 float activeTime = sortedPair.first;
3792 const BufferTuple& values = sortedPair.second;
3793 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3794 std::get<0>(values).c_str(), activeTime,
3795 std::get<1>(values), std::get<2>(values),
3796 std::get<3>(values));
3797 }
3798 result.append("\n");
3799}
3800
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003801void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3802 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003803 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003804
3805 // TODO: print out if wide-color mode is active or not
3806
3807 for (size_t d = 0; d < mDisplays.size(); d++) {
3808 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3809 int32_t hwcId = displayDevice->getHwcDisplayId();
3810 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3811 continue;
3812 }
3813
3814 result.appendFormat("Display %d color modes:\n", hwcId);
3815 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3816 for (auto&& mode : modes) {
3817 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3818 }
3819
3820 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3821 result.appendFormat(" Current color mode: %s (%d)\n",
3822 decodeColorMode(currentMode).c_str(), currentMode);
3823 }
3824 result.append("\n");
3825}
3826
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003827LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003828 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003829 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3830 const State& state = useDrawing ? mDrawingState : mCurrentState;
3831 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003832 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003833 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003834 });
3835
3836 return layersProto;
3837}
3838
Mathias Agopian74d211a2013-04-22 16:55:35 +02003839void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3840 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003841{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003842 bool colorize = false;
3843 if (index < args.size()
3844 && (args[index] == String16("--color"))) {
3845 colorize = true;
3846 index++;
3847 }
3848
3849 Colorizer colorizer(colorize);
3850
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003851 // figure out if we're stuck somewhere
3852 const nsecs_t now = systemTime();
3853 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3854 const nsecs_t inTransaction(mDebugInTransaction);
3855 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3856 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3857
3858 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003859 * Dump library configuration.
3860 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003861
3862 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003863 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003864 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003865 appendSfConfigString(result);
3866 appendUiConfigString(result);
3867 appendGuiConfigString(result);
3868 result.append("\n");
3869
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003870 result.append("\nWide-Color information:\n");
3871 dumpWideColorInfo(result);
3872
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003873 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003874 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003875 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003876 result.append(SyncFeatures::getInstance().toString());
3877 result.append("\n");
3878
Dan Stoza9e56aa02015-11-02 13:00:03 -08003879 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3880
Andy McFadden41d67d72014-04-25 16:58:34 -07003881 colorizer.bold(result);
3882 result.append("DispSync configuration: ");
3883 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003884 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003885 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003886 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003887 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003888 result.append("\n");
3889
Dan Stozab90cf072015-03-05 11:05:59 -08003890 // Dump static screen stats
3891 result.append("\n");
3892 dumpStaticScreenStats(result);
3893 result.append("\n");
3894
Dan Stozae77c7662016-05-13 11:37:28 -07003895 dumpBufferingStats(result);
3896
Andy McFadden4803b742012-09-24 19:07:20 -07003897 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003898 * Dump the visible layer list
3899 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003900 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003901 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003902 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003903
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003904 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003905 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3906 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003907
3908 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003909 * Dump Display state
3910 */
3911
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003912 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003913 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003914 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003915 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3916 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003917 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003918 }
3919
3920 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003921 * Dump SurfaceFlinger global state
3922 */
3923
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003924 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003925 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003926 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003927
Mathias Agopian888c8222012-08-04 21:10:38 -07003928 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003929 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003930
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003931 colorizer.bold(result);
3932 result.appendFormat("EGL implementation : %s\n",
3933 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3934 colorizer.reset(result);
3935 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003936 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003937
Mathias Agopian875d8e12013-06-07 15:35:48 -07003938 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003939
Mathias Agopian42977342012-08-05 00:40:46 -07003940 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003941 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3942 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003943 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003944 " last eglSwapBuffers() time: %f us\n"
3945 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003946 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003947 " refresh-rate : %f fps\n"
3948 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003949 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003950 " gpu_to_cpu_unsupported : %d\n"
3951 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003952 mLastSwapBufferTime/1000.0,
3953 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003954 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003955 1e9 / activeConfig->getVsyncPeriod(),
3956 activeConfig->getDpiX(),
3957 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003958 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003959
Mathias Agopian74d211a2013-04-22 16:55:35 +02003960 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003961 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003962
Mathias Agopian74d211a2013-04-22 16:55:35 +02003963 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003964 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003965
3966 /*
3967 * VSYNC state
3968 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003969 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003970 result.append("\n");
3971
3972 /*
3973 * HWC layer minidump
3974 */
3975 for (size_t d = 0; d < mDisplays.size(); d++) {
3976 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3977 int32_t hwcId = displayDevice->getHwcDisplayId();
3978 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3979 continue;
3980 }
3981
3982 result.appendFormat("Display %d HWC layers:\n", hwcId);
3983 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003984 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003985 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003986 });
Dan Stozae22aec72016-08-01 13:20:59 -07003987 result.append("\n");
3988 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003989
3990 /*
3991 * Dump HWComposer state
3992 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003993 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003994 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003995 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003996 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003997 result.appendFormat(" h/w composer %s\n",
3998 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003999 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004000
4001 /*
4002 * Dump gralloc state
4003 */
4004 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4005 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004006
4007 /*
4008 * Dump VrFlinger state if in use.
4009 */
4010 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4011 result.append("VrFlinger state:\n");
4012 result.append(mVrFlinger->Dump().c_str());
4013 result.append("\n");
4014 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004015}
4016
Mathias Agopian13127d82013-03-05 17:47:11 -08004017const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004018SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004019 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004020 wp<IBinder> dpy;
4021 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4022 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4023 dpy = mDisplays.keyAt(i);
4024 break;
4025 }
4026 }
4027 if (dpy == NULL) {
4028 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4029 // Just use the primary display so we have something to return
4030 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4031 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004032 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004033}
4034
Keun young Park63f165f2012-08-31 10:53:36 -07004035bool SurfaceFlinger::startDdmConnection()
4036{
4037 void* libddmconnection_dso =
4038 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4039 if (!libddmconnection_dso) {
4040 return false;
4041 }
4042 void (*DdmConnection_start)(const char* name);
4043 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004044 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004045 if (!DdmConnection_start) {
4046 dlclose(libddmconnection_dso);
4047 return false;
4048 }
4049 (*DdmConnection_start)(getServiceName());
4050 return true;
4051}
4052
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004053status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004054 switch (code) {
4055 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004056 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004057 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004058 case CLEAR_ANIMATION_FRAME_STATS:
4059 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004060 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004061 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004062 case ENABLE_VSYNC_INJECTIONS:
4063 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004064 {
4065 // codes that require permission check
4066 IPCThreadState* ipc = IPCThreadState::self();
4067 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004068 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004069 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004070 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004071 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004072 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004073 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004074 break;
4075 }
Robert Carr1db73f62016-12-21 12:58:51 -08004076 /*
4077 * Calling setTransactionState is safe, because you need to have been
4078 * granted a reference to Client* and Handle* to do anything with it.
4079 *
4080 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4081 */
4082 case SET_TRANSACTION_STATE:
4083 case CREATE_SCOPED_CONNECTION:
4084 {
4085 return OK;
4086 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004087 case CAPTURE_SCREEN:
4088 {
4089 // codes that require permission check
4090 IPCThreadState* ipc = IPCThreadState::self();
4091 const int pid = ipc->getCallingPid();
4092 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004093 if ((uid != AID_GRAPHICS) &&
4094 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004095 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004096 return PERMISSION_DENIED;
4097 }
4098 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004099 }
chaviwa76b2712017-09-20 12:02:26 -07004100 case CAPTURE_LAYERS: {
4101 IPCThreadState* ipc = IPCThreadState::self();
4102 const int pid = ipc->getCallingPid();
4103 const int uid = ipc->getCallingUid();
4104 if ((uid != AID_GRAPHICS) &&
4105 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4106 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4107 return PERMISSION_DENIED;
4108 }
4109 break;
4110 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004111 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004112 return OK;
4113}
4114
4115status_t SurfaceFlinger::onTransact(
4116 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4117{
4118 status_t credentialCheck = CheckTransactCodeCredentials(code);
4119 if (credentialCheck != OK) {
4120 return credentialCheck;
4121 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004123 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4124 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004125 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004126 IPCThreadState* ipc = IPCThreadState::self();
4127 const int uid = ipc->getCallingUid();
4128 if (CC_UNLIKELY(uid != AID_SYSTEM
4129 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004130 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004131 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004132 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004133 return PERMISSION_DENIED;
4134 }
4135 int n;
4136 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004137 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004138 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004139 return NO_ERROR;
4140 case 1002: // SHOW_UPDATES
4141 n = data.readInt32();
4142 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004143 invalidateHwcGeometry();
4144 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004145 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004146 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004147 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004148 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004149 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004150 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004151 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004152 setTransactionFlags(
4153 eTransactionNeeded|
4154 eDisplayTransactionNeeded|
4155 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004156 return NO_ERROR;
4157 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004158 case 1006:{ // send empty update
4159 signalRefresh();
4160 return NO_ERROR;
4161 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004162 case 1008: // toggle use of hw composer
4163 n = data.readInt32();
4164 mDebugDisableHWC = n ? 1 : 0;
4165 invalidateHwcGeometry();
4166 repaintEverything();
4167 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004168 case 1009: // toggle use of transform hint
4169 n = data.readInt32();
4170 mDebugDisableTransformHint = n ? 1 : 0;
4171 invalidateHwcGeometry();
4172 repaintEverything();
4173 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004174 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004175 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004176 reply->writeInt32(0);
4177 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004178 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004179 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004180 return NO_ERROR;
4181 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004182 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004183 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004184 return NO_ERROR;
4185 }
4186 case 1014: {
4187 // daltonize
4188 n = data.readInt32();
4189 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004190 case 1:
4191 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4192 break;
4193 case 2:
4194 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4195 break;
4196 case 3:
4197 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4198 break;
4199 default:
4200 mDaltonizer.setType(ColorBlindnessType::None);
4201 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004202 }
4203 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004204 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004205 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004206 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004207 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004208 invalidateHwcGeometry();
4209 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004210 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004211 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004212 case 1015: {
4213 // apply a color matrix
4214 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004215 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004216 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004217 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004218 for (size_t j = 0; j < 4; j++) {
4219 mColorMatrix[i][j] = data.readFloat();
4220 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004221 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004222 } else {
4223 mColorMatrix = mat4();
4224 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004225
4226 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4227 // the division by w in the fragment shader
4228 float4 lastRow(transpose(mColorMatrix)[3]);
4229 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4230 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4231 }
4232
Alan Viverette9c5a3332013-09-12 20:04:35 -07004233 invalidateHwcGeometry();
4234 repaintEverything();
4235 return NO_ERROR;
4236 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004237 // This is an experimental interface
4238 // Needs to be shifted to proper binder interface when we productize
4239 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004240 n = data.readInt32();
4241 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004242 return NO_ERROR;
4243 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004244 case 1017: {
4245 n = data.readInt32();
4246 mForceFullDamage = static_cast<bool>(n);
4247 return NO_ERROR;
4248 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004249 case 1018: { // Modify Choreographer's phase offset
4250 n = data.readInt32();
4251 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4252 return NO_ERROR;
4253 }
4254 case 1019: { // Modify SurfaceFlinger's phase offset
4255 n = data.readInt32();
4256 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4257 return NO_ERROR;
4258 }
Irvel468051e2016-06-13 16:44:44 -07004259 case 1020: { // Layer updates interceptor
4260 n = data.readInt32();
4261 if (n) {
4262 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004263 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004264 }
4265 else{
4266 ALOGV("Interceptor disabled");
4267 mInterceptor.disable();
4268 }
4269 return NO_ERROR;
4270 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004271 case 1021: { // Disable HWC virtual displays
4272 n = data.readInt32();
4273 mUseHwcVirtualDisplays = !n;
4274 return NO_ERROR;
4275 }
Romain Guy0147a172017-06-01 13:53:56 -07004276 case 1022: { // Set saturation boost
4277 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4278
4279 invalidateHwcGeometry();
4280 repaintEverything();
4281 return NO_ERROR;
4282 }
Romain Guy54f154a2017-10-24 21:40:32 +01004283 case 1023: { // Set native mode
4284 mForceNativeColorMode = data.readInt32() == 1;
4285
4286 invalidateHwcGeometry();
4287 repaintEverything();
4288 return NO_ERROR;
4289 }
4290 case 1024: { // Is wide color gamut rendering/color management supported?
4291 reply->writeBool(hasWideColorDisplay);
4292 return NO_ERROR;
4293 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004294 case 1025: { // tracing
4295 n = data.readInt32();
4296 if (n) {
4297 ALOGV("LayerTracing enabled");
4298 mTracing.enable();
4299 doTracing("tracing.enable");
4300 reply->writeInt32(NO_ERROR);
4301 } else {
4302 ALOGV("LayerTracing disabled");
4303 status_t err = mTracing.disable();
4304 reply->writeInt32(err);
4305 }
4306 return NO_ERROR;
4307 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004308 }
4309 }
4310 return err;
4311}
4312
Steven Thomas6d8110b2017-08-31 18:24:21 -07004313void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004314 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004315 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004316}
4317
Steven Thomas6d8110b2017-08-31 18:24:21 -07004318void SurfaceFlinger::repaintEverything() {
4319 ConditionalLock _l(mStateLock,
4320 std::this_thread::get_id() != mMainThreadId);
4321 repaintEverythingLocked();
4322}
4323
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004324// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4325class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004326public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004327 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4328 ~WindowDisconnector() {
4329 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004330 }
4331
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004332private:
4333 ANativeWindow* mWindow;
4334 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004335};
4336
chaviwa252d892017-11-20 17:54:25 -08004337status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4338 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4339 int32_t minLayerZ, int32_t maxLayerZ,
4340 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004341 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004342 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004343
chaviwa76b2712017-09-20 12:02:26 -07004344 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4345
4346 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4347 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4348
4349 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4350 device, minLayerZ, maxLayerZ, std::placeholders::_1);
chaviwa252d892017-11-20 17:54:25 -08004351 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004352}
4353
4354status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
chaviwa252d892017-11-20 17:54:25 -08004355 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
4356 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004357 ATRACE_CALL();
4358
4359 class LayerRenderArea : public RenderArea {
4360 public:
chaviw7206d492017-11-10 16:16:12 -08004361 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
chaviwa252d892017-11-20 17:54:25 -08004362 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004363 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004364 const Transform& getTransform() const override {
4365 // Make the top level transform the inverse the transform and it's parent so it sets
4366 // the whole capture back to 0,0
4367 return *new Transform(mLayer->getTransform().inverse());
4368 }
4369 Rect getBounds() const override {
4370 const Layer::State& layerState(mLayer->getDrawingState());
4371 return Rect(layerState.active.w, layerState.active.h);
4372 }
4373 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4374 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4375 bool isSecure() const override { return false; }
4376 bool needsFiltering() const override { return false; }
4377
chaviw7206d492017-11-10 16:16:12 -08004378 Rect getSourceCrop() const override {
4379 if (mCrop.isEmpty()) {
4380 return getBounds();
4381 } else {
4382 return mCrop;
4383 }
4384 }
chaviwa76b2712017-09-20 12:02:26 -07004385 bool getWideColorSupport() const override { return false; }
4386 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4387
4388 private:
chaviw7206d492017-11-10 16:16:12 -08004389 const sp<Layer> mLayer;
4390 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004391 };
4392
4393 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4394 auto parent = layerHandle->owner.promote();
4395
chaviw7206d492017-11-10 16:16:12 -08004396 if (parent == nullptr || parent->isPendingRemoval()) {
4397 ALOGE("captureLayers called with a removed parent");
4398 return NAME_NOT_FOUND;
4399 }
4400
4401 Rect crop(sourceCrop);
4402 if (sourceCrop.width() <= 0) {
4403 crop.left = 0;
4404 crop.right = parent->getCurrentState().active.w;
4405 }
4406
4407 if (sourceCrop.height() <= 0) {
4408 crop.top = 0;
4409 crop.bottom = parent->getCurrentState().active.h;
4410 }
4411
4412 int32_t reqWidth = crop.width() * frameScale;
4413 int32_t reqHeight = crop.height() * frameScale;
4414
4415 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4416
chaviwa76b2712017-09-20 12:02:26 -07004417 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4418 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4419 if (!layer->isVisible()) {
4420 return;
4421 }
4422 visitor(layer);
4423 });
4424 };
chaviwa252d892017-11-20 17:54:25 -08004425 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004426}
4427
4428status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4429 TraverseLayersFunction traverseLayers,
chaviwa252d892017-11-20 17:54:25 -08004430 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004431 bool useIdentityTransform) {
4432 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004433
chaviwa76b2712017-09-20 12:02:26 -07004434 renderArea.updateDimensions();
4435
chaviwa252d892017-11-20 17:54:25 -08004436 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4437 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4438 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4439 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004440
4441 // This mutex protects syncFd and captureResult for communication of the return values from the
4442 // main thread back to this Binder thread
4443 std::mutex captureMutex;
4444 std::condition_variable captureCondition;
4445 std::unique_lock<std::mutex> captureLock(captureMutex);
4446 int syncFd = -1;
4447 std::optional<status_t> captureResult;
4448
4449 sp<LambdaMessage> message = new LambdaMessage([&]() {
4450 // If there is a refresh pending, bug out early and tell the binder thread to try again
4451 // after the refresh.
4452 if (mRefreshPending) {
4453 ATRACE_NAME("Skipping screenshot for now");
4454 std::unique_lock<std::mutex> captureLock(captureMutex);
4455 captureResult = std::make_optional<status_t>(EAGAIN);
4456 captureCondition.notify_one();
4457 return;
4458 }
4459
4460 status_t result = NO_ERROR;
4461 int fd = -1;
4462 {
4463 Mutex::Autolock _l(mStateLock);
chaviwa252d892017-11-20 17:54:25 -08004464 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4465 useIdentityTransform, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004466 }
4467
4468 {
4469 std::unique_lock<std::mutex> captureLock(captureMutex);
4470 syncFd = fd;
4471 captureResult = std::make_optional<status_t>(result);
4472 captureCondition.notify_one();
4473 }
4474 });
4475
chaviwa252d892017-11-20 17:54:25 -08004476 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004477 if (result == NO_ERROR) {
4478 captureCondition.wait(captureLock, [&]() { return captureResult; });
4479 while (*captureResult == EAGAIN) {
4480 captureResult.reset();
4481 result = postMessageAsync(message);
4482 if (result != NO_ERROR) {
4483 return result;
4484 }
4485 captureCondition.wait(captureLock, [&]() { return captureResult; });
4486 }
4487 result = *captureResult;
4488 }
4489
4490 if (result == NO_ERROR) {
chaviwa252d892017-11-20 17:54:25 -08004491 sync_wait(syncFd, -1);
4492 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004493 }
chaviwa252d892017-11-20 17:54:25 -08004494
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004495 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004496}
4497
chaviwa76b2712017-09-20 12:02:26 -07004498void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4499 TraverseLayersFunction traverseLayers, bool yswap,
4500 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004501 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004502
Mathias Agopian3f844832013-08-07 21:24:32 -07004503 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004504
4505 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004506 const auto raWidth = renderArea.getWidth();
4507 const auto raHeight = renderArea.getHeight();
4508
4509 const auto reqWidth = renderArea.getReqWidth();
4510 const auto reqHeight = renderArea.getReqHeight();
4511 Rect sourceCrop = renderArea.getSourceCrop();
4512
4513 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4514 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004515
Dan Stozac1879002014-05-22 15:59:05 -07004516 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004517 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004518 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004519 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004520 }
4521
4522 // ensure that sourceCrop is inside screen
4523 if (sourceCrop.left < 0) {
4524 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4525 }
chaviwa76b2712017-09-20 12:02:26 -07004526 if (sourceCrop.right > raWidth) {
4527 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004528 }
4529 if (sourceCrop.top < 0) {
4530 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4531 }
chaviwa76b2712017-09-20 12:02:26 -07004532 if (sourceCrop.bottom > raHeight) {
4533 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004534 }
4535
chaviwa76b2712017-09-20 12:02:26 -07004536 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
chaviwa252d892017-11-20 17:54:25 -08004537 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4538 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004539
Mathias Agopian180f10d2013-04-10 22:55:41 -07004540 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004541 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004542
4543 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004544 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4545 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004546 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004547
4548 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004549 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004550
chaviwa76b2712017-09-20 12:02:26 -07004551 traverseLayers([&](Layer* layer) {
4552 if (filtering) layer->setFiltering(true);
4553 layer->draw(renderArea, useIdentityTransform);
4554 if (filtering) layer->setFiltering(false);
4555 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004556}
4557
Dan Stozaabcda352017-06-01 14:37:39 -07004558// A simple RAII class that holds an EGLImage and destroys it either:
4559// a) When the destroy() method is called
4560// b) When the object goes out of scope
4561class ImageHolder {
4562public:
4563 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4564 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004565
Dan Stozaabcda352017-06-01 14:37:39 -07004566 void destroy() {
4567 if (mImage != EGL_NO_IMAGE_KHR) {
4568 eglDestroyImageKHR(mDisplay, mImage);
4569 mImage = EGL_NO_IMAGE_KHR;
4570 }
4571 }
4572
4573private:
4574 const EGLDisplay mDisplay;
4575 EGLImageKHR mImage;
4576};
4577
chaviwa76b2712017-09-20 12:02:26 -07004578status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4579 TraverseLayersFunction traverseLayers,
4580 ANativeWindowBuffer* buffer,
chaviwa252d892017-11-20 17:54:25 -08004581 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004582 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004583 ATRACE_CALL();
4584
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004585 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004586
4587 traverseLayers([&](Layer* layer) {
4588 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4589 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004590
chaviwa252d892017-11-20 17:54:25 -08004591 if (secureLayerIsVisible) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004592 ALOGW("FB is protected: PERMISSION_DENIED");
4593 return PERMISSION_DENIED;
4594 }
4595
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004596 int syncFd = -1;
4597 // create an EGLImage from the buffer so we can later
4598 // turn it into a texture
4599 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4600 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4601 if (image == EGL_NO_IMAGE_KHR) {
4602 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004603 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004604
Dan Stozaabcda352017-06-01 14:37:39 -07004605 // This will automatically destroy the image if we return before calling its destroy method
4606 ImageHolder imageHolder(mEGLDisplay, image);
4607
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004608 // this binds the given EGLImage as a framebuffer for the
4609 // duration of this scope.
4610 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004611 if (imageBond.getStatus() != NO_ERROR) {
4612 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004613 return INVALID_OPERATION;
4614 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004615
Dan Stozaabcda352017-06-01 14:37:39 -07004616 // this will in fact render into our dequeued buffer
4617 // via an FBO, which means we didn't have to create
4618 // an EGLSurface and therefore we're not
4619 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004620 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004621
Dan Stozaabcda352017-06-01 14:37:39 -07004622 // Attempt to create a sync khr object that can produce a sync point. If that
4623 // isn't available, create a non-dupable sync object in the fallback path and
4624 // wait on it directly.
4625 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4626 if (!DEBUG_SCREENSHOTS) {
4627 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4628 // native fence fd will not be populated until flush() is done.
4629 getRenderEngine().flush();
4630 }
4631
4632 if (sync != EGL_NO_SYNC_KHR) {
4633 // get the sync fd
4634 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4635 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4636 ALOGW("captureScreen: failed to dup sync khr object");
4637 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004638 }
Dan Stozaabcda352017-06-01 14:37:39 -07004639 eglDestroySyncKHR(mEGLDisplay, sync);
4640 } else {
4641 // fallback path
4642 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004643 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004644 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4645 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4646 EGLint eglErr = eglGetError();
4647 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4648 ALOGW("captureScreen: fence wait timed out");
4649 } else {
4650 ALOGW_IF(eglErr != EGL_SUCCESS,
4651 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004652 }
4653 eglDestroySyncKHR(mEGLDisplay, sync);
4654 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004655 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004656 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004657 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004658 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004659
4660 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004661 const auto reqWidth = renderArea.getReqWidth();
4662 const auto reqHeight = renderArea.getReqHeight();
4663
Dan Stozaabcda352017-06-01 14:37:39 -07004664 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4665 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004666 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004667 delete [] pixels;
4668 }
4669
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004670 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004671 imageHolder.destroy();
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004672 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004673}
4674
Mathias Agopiand5556842013-09-19 17:08:37 -07004675void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004676 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004677 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004678 for (size_t y = 0; y < h; y++) {
4679 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4680 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004681 if (p[x] != 0xFF000000) return;
4682 }
4683 }
chaviwa76b2712017-09-20 12:02:26 -07004684 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004685
Robert Carr2047fae2016-11-28 14:09:09 -08004686 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004687 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004688 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004689 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4690 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4691 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4692 static_cast<float>(state.color.a));
4693 i++;
4694 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004695 }
4696}
4697
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004698// ---------------------------------------------------------------------------
4699
Dan Stoza412903f2017-04-27 13:42:17 -07004700void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4701 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004702}
4703
Dan Stoza412903f2017-04-27 13:42:17 -07004704void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4705 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004706}
4707
chaviwa76b2712017-09-20 12:02:26 -07004708void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4709 int32_t maxLayerZ,
4710 const LayerVector::Visitor& visitor) {
4711 // We loop through the first level of layers without traversing,
4712 // as we need to interpret min/max layer Z in the top level Z space.
4713 for (const auto& layer : mDrawingState.layersSortedByZ) {
4714 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4715 continue;
4716 }
4717 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004718 // relative layers are traversed in Layer::traverseInZOrder
4719 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004720 continue;
4721 }
4722 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4723 if (!layer->isVisible()) {
4724 return;
4725 }
4726 visitor(layer);
4727 });
4728 }
4729}
4730
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004731}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004732
4733
4734#if defined(__gl_h_)
4735#error "don't include gl/gl.h in this file"
4736#endif
4737
4738#if defined(__gl2_h_)
4739#error "don't include gl2/gl2.h in this file"
chaviwa252d892017-11-20 17:54:25 -08004740#endif