blob: 624fda27f44f844c32e56b735361435549de9f84 [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"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093#define DISPLAY_COUNT 1
94
Mathias Agopianfee2b462013-07-03 12:34:01 -070095/*
96 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
97 * black pixels.
98 */
99#define DEBUG_SCREENSHOTS false
100
Jiyong Park00b15b82017-08-10 20:30:56 +0900101extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
Mathias Agopianca088332013-03-28 17:44:13 -0700102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
Steven Thomasb02664d2017-07-26 18:48:28 -0700108namespace {
109class ConditionalLock {
110public:
111 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
112 if (lock) {
113 mMutex.lock();
114 }
115 }
116 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
117private:
118 Mutex& mMutex;
119 bool mLocked;
120};
121} // namespace anonymous
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800131int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
132int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700133bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700134int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700135bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800136uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800137bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800138bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800139int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700158 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700160 mTransactionPending(false),
161 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700162 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700163 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700164 mRepaintEverything(0),
Kalle Raitaa099a242017-01-11 11:17:29 -0800165 mHwcServiceName(getHwcServiceName()),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800166 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800168 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800170 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800171 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800172 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700173 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700174 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700175 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700176 mDebugInSwapBuffers(0),
177 mLastSwapBufferTime(0),
178 mDebugInTransaction(0),
179 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700180 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700181 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800182 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000183 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700184 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700185 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700186 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800187 mHasPoweredOff(false),
188 mFrameBuckets(),
189 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700190 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800191 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700192 mVrFlingerRequestsDisplay(false),
193 mMainThreadId(std::this_thread::get_id()),
194 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800196 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800197
198 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
199 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
200
201 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
202 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
203
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800204 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
205 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700207 useContextPriority = getBool< ISurfaceFlingerConfigs,
208 &ISurfaceFlingerConfigs::useContextPriority>(false);
209
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700210 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
211 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
212
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700213 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
214 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
215
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
217 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
218
Steven Thomas050b2c82017-03-06 11:45:16 -0800219 // Vr flinger is only enabled on Daydream ready devices.
220 useVrFlinger = getBool< ISurfaceFlingerConfigs,
221 &ISurfaceFlingerConfigs::useVrFlinger>(false);
222
Fabien Sanglard1971b632017-03-10 14:50:03 -0800223 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
224 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
225
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600226 hasWideColorDisplay =
227 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
228
Saurabh Shahf4174532017-07-13 10:45:07 -0700229 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
230
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 // debugging stuff...
232 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700233
Mathias Agopianb4b17302013-03-20 18:36:41 -0700234 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700235 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 property_get("debug.sf.showupdates", value, "0");
238 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240 property_get("debug.sf.ddms", value, "0");
241 mDebugDDMS = atoi(value);
242 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700243 if (!startDdmConnection()) {
244 // start failed, and DDMS debugging not enabled
245 mDebugDDMS = 0;
246 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700247 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700248 ALOGI_IF(mDebugRegion, "showupdates enabled");
249 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700250
251 property_get("debug.sf.disable_backpressure", value, "0");
252 mPropagateBackpressure = !atoi(value);
253 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700254
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800255 property_get("debug.sf.enable_hwc_vds", value, "0");
256 mUseHwcVirtualDisplays = atoi(value);
257 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800258
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800259 property_get("ro.sf.disable_triple_buffer", value, "1");
260 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800261 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700262
Romain Guy11d63f42017-07-20 12:47:14 -0700263 // We should be reading 'persist.sys.sf.color_saturation' here
264 // but since /data may be encrypted, we need to wait until after vold
265 // comes online to attempt to read the property. The property is
266 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800267
268 if (useTrebleTestingOverride()) {
269 // Without the override SurfaceFlinger cannot connect to HIDL
270 // services that are not listed in the manifests. Considered
271 // deriving the setting from the set service name, but it
272 // would be brittle if the name that's not 'default' is used
273 // for production purposes later on.
274 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800278void SurfaceFlinger::onFirstRef()
279{
280 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800281}
282
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283SurfaceFlinger::~SurfaceFlinger()
284{
Mathias Agopiana4912602012-07-12 14:25:33 -0700285 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
286 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
287 eglTerminate(display);
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);
571 mCallback->onVSyncEvent(when);
572 }
573
574 virtual void setVSyncEnabled(bool) {}
575 virtual void setPhaseOffset(nsecs_t) {}
576
577private:
578 std::mutex mCallbackMutex; // Protects the following
579 sp<VSyncSource::Callback> mCallback;
580};
581
Wei Wangf9b05ee2017-07-19 20:59:39 -0700582// Do not call property_set on main thread which will be blocked by init
583// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700584void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700585 ALOGI( "SurfaceFlinger's main thread ready to run. "
586 "Initializing graphics H/W...");
587
Thierry Strudel2924d012017-08-14 15:19:37 -0700588 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900589
Steven Thomasb02664d2017-07-26 18:48:28 -0700590 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800591
Steven Thomasb02664d2017-07-26 18:48:28 -0700592 // initialize EGL for the default display
593 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
594 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800595
Steven Thomasb02664d2017-07-26 18:48:28 -0700596 // start the EventThread
597 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
598 vsyncPhaseOffsetNs, true, "app");
599 mEventThread = new EventThread(vsyncSrc, *this, false);
600 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
601 sfVsyncPhaseOffsetNs, true, "sf");
602 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
603 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800604
Steven Thomasb02664d2017-07-26 18:48:28 -0700605 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
606 struct sched_param param = {0};
607 param.sched_priority = 2;
608 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
609 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
610 }
611 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
612 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800613 }
614
Steven Thomasb02664d2017-07-26 18:48:28 -0700615 // Get a RenderEngine for the given display / config (can't fail)
616 mRenderEngine = RenderEngine::create(mEGLDisplay,
617 HAL_PIXEL_FORMAT_RGBA_8888,
618 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 // retrieve the EGL context that was selected/created
621 mEGLContext = mRenderEngine->getEGLContext();
622
623 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
624 "couldn't create EGLContext");
625
626 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
627 "Starting with vr flinger active is not currently supported.");
628 mHwc.reset(new HWComposer(mHwcServiceName));
629 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800630
Steven Thomas050b2c82017-03-06 11:45:16 -0800631 if (useVrFlinger) {
632 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700633 // This callback is called from the vr flinger dispatch thread. We
634 // need to call signalTransaction(), which requires holding
635 // mStateLock when we're not on the main thread. Acquiring
636 // mStateLock from the vr flinger dispatch thread might trigger a
637 // deadlock in surface flinger (see b/66916578), so post a message
638 // to be handled on the main thread instead.
639 sp<LambdaMessage> message = new LambdaMessage([=]() {
640 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
641 mVrFlingerRequestsDisplay = requestDisplay;
642 signalTransaction();
643 });
644 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800645 };
646 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
647 vrFlingerRequestDisplayCallback);
648 if (!mVrFlinger) {
649 ALOGE("Failed to start vrflinger");
650 }
651 }
652
Jamie Gennisd1700752013-10-14 12:22:52 -0700653 mEventControlThread = new EventControlThread(this);
654 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
655
Mathias Agopian92a979a2012-08-02 18:32:23 -0700656 // initialize our drawing state
657 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700658
Andy McFadden13a082e2012-08-24 10:16:42 -0700659 // set initial conditions (e.g. unblank default device)
660 initializeDisplays();
661
Dan Stoza4e637772016-07-28 13:31:51 -0700662 mRenderEngine->primeCache();
663
Wei Wangf9b05ee2017-07-19 20:59:39 -0700664 // Inform native graphics APIs whether the present timestamp is supported:
665 if (getHwComposer().hasCapability(
666 HWC2::Capability::PresentFenceIsNotReliable)) {
667 mStartPropertySetThread = new StartPropertySetThread(false);
668 } else {
669 mStartPropertySetThread = new StartPropertySetThread(true);
670 }
671
672 if (mStartPropertySetThread->Start() != NO_ERROR) {
673 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800674 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800675
Dan Stoza9e56aa02015-11-02 13:00:03 -0800676 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700677}
678
Romain Guy11d63f42017-07-20 12:47:14 -0700679void SurfaceFlinger::readPersistentProperties() {
680 char value[PROPERTY_VALUE_MAX];
681
682 property_get("persist.sys.sf.color_saturation", value, "1.0");
683 mSaturation = atof(value);
684 ALOGV("Saturation is set to %.2f", mSaturation);
685}
686
Mathias Agopiana67e4182012-06-19 17:26:12 -0700687void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800688 // Start boot animation service by setting a property mailbox
689 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700690 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800691 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 if (mStartPropertySetThread->join() != NO_ERROR) {
693 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800694 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700695}
696
Mathias Agopian875d8e12013-06-07 15:35:48 -0700697size_t SurfaceFlinger::getMaxTextureSize() const {
698 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700699}
700
Mathias Agopian875d8e12013-06-07 15:35:48 -0700701size_t SurfaceFlinger::getMaxViewportDims() const {
702 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700703}
704
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800705// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800706
Jamie Gennis582270d2011-08-17 18:19:00 -0700707bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800708 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800709 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800710 return authenticateSurfaceTextureLocked(bufferProducer);
711}
712
713bool SurfaceFlinger::authenticateSurfaceTextureLocked(
714 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800715 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700716 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800717}
718
Brian Anderson6b376712017-04-04 10:51:39 -0700719status_t SurfaceFlinger::getSupportedFrameTimestamps(
720 std::vector<FrameEvent>* outSupported) const {
721 *outSupported = {
722 FrameEvent::REQUESTED_PRESENT,
723 FrameEvent::ACQUIRE,
724 FrameEvent::LATCH,
725 FrameEvent::FIRST_REFRESH_START,
726 FrameEvent::LAST_REFRESH_START,
727 FrameEvent::GPU_COMPOSITION_DONE,
728 FrameEvent::DEQUEUE_READY,
729 FrameEvent::RELEASE,
730 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700731 ConditionalLock _l(mStateLock,
732 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700733 if (!getHwComposer().hasCapability(
734 HWC2::Capability::PresentFenceIsNotReliable)) {
735 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
736 }
737 return NO_ERROR;
738}
739
Dan Stoza7f7da322014-05-02 15:26:25 -0700740status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
741 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700742 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700743 return BAD_VALUE;
744 }
745
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500746 if (!display.get())
747 return NAME_NOT_FOUND;
748
Jesse Hall692c7232012-11-08 15:41:56 -0800749 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700750 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800751 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700752 type = i;
753 break;
754 }
755 }
756
757 if (type < 0) {
758 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700759 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700760
Mathias Agopian8b736f12012-08-13 17:54:26 -0700761 // TODO: Not sure if display density should handled by SF any longer
762 class Density {
763 static int getDensityFromProperty(char const* propName) {
764 char property[PROPERTY_VALUE_MAX];
765 int density = 0;
766 if (property_get(propName, property, NULL) > 0) {
767 density = atoi(property);
768 }
769 return density;
770 }
771 public:
772 static int getEmuDensity() {
773 return getDensityFromProperty("qemu.sf.lcd_density"); }
774 static int getBuildDensity() {
775 return getDensityFromProperty("ro.sf.lcd_density"); }
776 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700777
Dan Stoza7f7da322014-05-02 15:26:25 -0700778 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700779
Steven Thomas6d8110b2017-08-31 18:24:21 -0700780 ConditionalLock _l(mStateLock,
781 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800782 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700783 DisplayInfo info = DisplayInfo();
784
Dan Stoza9e56aa02015-11-02 13:00:03 -0800785 float xdpi = hwConfig->getDpiX();
786 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700787
788 if (type == DisplayDevice::DISPLAY_PRIMARY) {
789 // The density of the device is provided by a build property
790 float density = Density::getBuildDensity() / 160.0f;
791 if (density == 0) {
792 // the build doesn't provide a density -- this is wrong!
793 // use xdpi instead
794 ALOGE("ro.sf.lcd_density must be defined as a build property");
795 density = xdpi / 160.0f;
796 }
797 if (Density::getEmuDensity()) {
798 // if "qemu.sf.lcd_density" is specified, it overrides everything
799 xdpi = ydpi = density = Density::getEmuDensity();
800 density /= 160.0f;
801 }
802 info.density = density;
803
804 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700805 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000806 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700807 } else {
808 // TODO: where should this value come from?
809 static const int TV_DENSITY = 213;
810 info.density = TV_DENSITY / 160.0f;
811 info.orientation = 0;
812 }
813
Dan Stoza9e56aa02015-11-02 13:00:03 -0800814 info.w = hwConfig->getWidth();
815 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700816 info.xdpi = xdpi;
817 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800818 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900819 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820
Andy McFadden91b2ca82014-06-13 14:04:23 -0700821 // This is how far in advance a buffer must be queued for
822 // presentation at a given time. If you want a buffer to appear
823 // on the screen at time N, you must submit the buffer before
824 // (N - presentationDeadline).
825 //
826 // Normally it's one full refresh period (to give SF a chance to
827 // latch the buffer), but this can be reduced by configuring a
828 // DispSync offset. Any additional delays introduced by the hardware
829 // composer or panel must be accounted for here.
830 //
831 // We add an additional 1ms to allow for processing time and
832 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800834 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700835
836 // All non-virtual displays are currently considered secure.
837 info.secure = true;
838
Michael Wright28f24d02016-07-12 13:30:53 -0700839 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 }
841
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 return NO_ERROR;
843}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700844
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800845status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700846 DisplayStatInfo* stats) {
847 if (stats == NULL) {
848 return BAD_VALUE;
849 }
850
851 // FIXME for now we always return stats for the primary display
852 memset(stats, 0, sizeof(*stats));
853 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
854 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
855 return NO_ERROR;
856}
857
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700858int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800859 if (display == NULL) {
860 ALOGE("%s : display is NULL", __func__);
861 return BAD_VALUE;
862 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700863
864 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700865 if (device != NULL) {
866 return device->getActiveConfig();
867 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700868
Dan Stoza24a42e92015-03-09 10:04:11 -0700869 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700870}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700871
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700872void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
873 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
874 this);
875 int32_t type = hw->getDisplayType();
876 int currentMode = hw->getActiveConfig();
877
878 if (mode == currentMode) {
879 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
880 return;
881 }
882
883 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
884 ALOGW("Trying to set config for virtual display");
885 return;
886 }
887
888 hw->setActiveConfig(mode);
889 getHwComposer().setActiveConfig(type, mode);
890}
891
892status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
893 class MessageSetActiveConfig: public MessageBase {
894 SurfaceFlinger& mFlinger;
895 sp<IBinder> mDisplay;
896 int mMode;
897 public:
898 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
899 int mode) :
900 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
901 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700902 Vector<DisplayInfo> configs;
903 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700904 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700905 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700906 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700907 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700908 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700909 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
910 if (hw == NULL) {
911 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700912 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700913 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
914 ALOGW("Attempt to set active config = %d for virtual display",
915 mMode);
916 } else {
917 mFlinger.setActiveConfigInternal(hw, mMode);
918 }
919 return true;
920 }
921 };
922 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
923 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700924 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700925}
Michael Wright28f24d02016-07-12 13:30:53 -0700926status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
927 Vector<android_color_mode_t>* outColorModes) {
928 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
929 return BAD_VALUE;
930 }
931
932 if (!display.get()) {
933 return NAME_NOT_FOUND;
934 }
935
936 int32_t type = NAME_NOT_FOUND;
937 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
938 if (display == mBuiltinDisplays[i]) {
939 type = i;
940 break;
941 }
942 }
943
944 if (type < 0) {
945 return type;
946 }
947
Steven Thomas6d8110b2017-08-31 18:24:21 -0700948 std::vector<android_color_mode_t> modes;
949 {
950 ConditionalLock _l(mStateLock,
951 std::this_thread::get_id() != mMainThreadId);
952 modes = getHwComposer().getColorModes(type);
953 }
Michael Wright28f24d02016-07-12 13:30:53 -0700954 outColorModes->clear();
955 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
956
957 return NO_ERROR;
958}
959
960android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700961 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700962 if (device != nullptr) {
963 return device->getActiveColorMode();
964 }
965 return static_cast<android_color_mode_t>(BAD_VALUE);
966}
967
968void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
969 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700970 int32_t type = hw->getDisplayType();
971 android_color_mode_t currentMode = hw->getActiveColorMode();
972
973 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700974 return;
975 }
976
977 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
978 ALOGW("Trying to set config for virtual display");
979 return;
980 }
981
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600982 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
983 hw->getDisplayType());
984
Michael Wright28f24d02016-07-12 13:30:53 -0700985 hw->setActiveColorMode(mode);
986 getHwComposer().setActiveColorMode(type, mode);
987}
988
989
990status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
991 android_color_mode_t colorMode) {
992 class MessageSetActiveColorMode: public MessageBase {
993 SurfaceFlinger& mFlinger;
994 sp<IBinder> mDisplay;
995 android_color_mode_t mMode;
996 public:
997 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
998 android_color_mode_t mode) :
999 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1000 virtual bool handler() {
1001 Vector<android_color_mode_t> modes;
1002 mFlinger.getDisplayColorModes(mDisplay, &modes);
1003 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1004 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001005 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1006 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001007 return true;
1008 }
1009 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1010 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001011 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1012 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001013 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001014 ALOGW("Attempt to set active color mode %s %d for virtual display",
1015 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001016 } else {
1017 mFlinger.setActiveColorModeInternal(hw, mMode);
1018 }
1019 return true;
1020 }
1021 };
1022 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1023 postMessageSync(msg);
1024 return NO_ERROR;
1025}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001026
Svetoslavd85084b2014-03-20 10:28:31 -07001027status_t SurfaceFlinger::clearAnimationFrameStats() {
1028 Mutex::Autolock _l(mStateLock);
1029 mAnimFrameTracker.clearStats();
1030 return NO_ERROR;
1031}
1032
1033status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1034 Mutex::Autolock _l(mStateLock);
1035 mAnimFrameTracker.getStats(outStats);
1036 return NO_ERROR;
1037}
1038
Dan Stozac4f471e2016-03-24 09:31:08 -07001039status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1040 HdrCapabilities* outCapabilities) const {
1041 Mutex::Autolock _l(mStateLock);
1042
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001043 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001044 if (displayDevice == nullptr) {
1045 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1046 return BAD_VALUE;
1047 }
1048
1049 std::unique_ptr<HdrCapabilities> capabilities =
1050 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1051 if (capabilities) {
1052 std::swap(*outCapabilities, *capabilities);
1053 } else {
1054 return BAD_VALUE;
1055 }
1056
1057 return NO_ERROR;
1058}
1059
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001060status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1061 if (enable == mInjectVSyncs) {
1062 return NO_ERROR;
1063 }
1064
1065 if (enable) {
1066 mInjectVSyncs = enable;
1067 ALOGV("VSync Injections enabled");
1068 if (mVSyncInjector.get() == nullptr) {
1069 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001070 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001071 }
1072 mEventQueue.setEventThread(mInjectorEventThread);
1073 } else {
1074 mInjectVSyncs = enable;
1075 ALOGV("VSync Injections disabled");
1076 mEventQueue.setEventThread(mSFEventThread);
1077 mVSyncInjector.clear();
1078 }
1079 return NO_ERROR;
1080}
1081
1082status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1083 if (!mInjectVSyncs) {
1084 ALOGE("VSync Injections not enabled");
1085 return BAD_VALUE;
1086 }
1087 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1088 ALOGV("Injecting VSync inside SurfaceFlinger");
1089 mVSyncInjector->onInjectSyncEvent(when);
1090 }
1091 return NO_ERROR;
1092}
1093
Kalle Raitaa099a242017-01-11 11:17:29 -08001094status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1095 IPCThreadState* ipc = IPCThreadState::self();
1096 const int pid = ipc->getCallingPid();
1097 const int uid = ipc->getCallingUid();
1098 if ((uid != AID_SHELL) &&
1099 !PermissionCache::checkPermission(sDump, pid, uid)) {
1100 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1101 return PERMISSION_DENIED;
1102 }
1103
1104 // Try to acquire a lock for 1s, fail gracefully
1105 const status_t err = mStateLock.timedLock(s2ns(1));
1106 const bool locked = (err == NO_ERROR);
1107 if (!locked) {
1108 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1109 return TIMED_OUT;
1110 }
1111
1112 outLayers->clear();
1113 mCurrentState.traverseInZOrder([&](Layer* layer) {
1114 outLayers->push_back(layer->getLayerDebugInfo());
1115 });
1116
1117 mStateLock.unlock();
1118 return NO_ERROR;
1119}
1120
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001121// ----------------------------------------------------------------------------
1122
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001123sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1124 ISurfaceComposer::VsyncSource vsyncSource) {
1125 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1126 return mSFEventThread->createEventConnection();
1127 } else {
1128 return mEventThread->createEventConnection();
1129 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001130}
1131
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001132// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001133
1134void SurfaceFlinger::waitForEvent() {
1135 mEventQueue.waitMessage();
1136}
1137
1138void SurfaceFlinger::signalTransaction() {
1139 mEventQueue.invalidate();
1140}
1141
1142void SurfaceFlinger::signalLayerUpdate() {
1143 mEventQueue.invalidate();
1144}
1145
1146void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001147 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001148 mEventQueue.refresh();
1149}
1150
1151status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001152 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001153 return mEventQueue.postMessage(msg, reltime);
1154}
1155
1156status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001157 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001158 status_t res = mEventQueue.postMessage(msg, reltime);
1159 if (res == NO_ERROR) {
1160 msg->wait();
1161 }
1162 return res;
1163}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001164
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001165void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001166 do {
1167 waitForEvent();
1168 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001169}
1170
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001171void SurfaceFlinger::enableHardwareVsync() {
1172 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001173 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001174 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001175 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1176 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001177 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001178 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001179}
1180
Jesse Hall948fe0c2013-10-14 12:56:09 -07001181void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001182 Mutex::Autolock _l(mHWVsyncLock);
1183
Jesse Hall948fe0c2013-10-14 12:56:09 -07001184 if (makeAvailable) {
1185 mHWVsyncAvailable = true;
1186 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001187 // Hardware vsync is not currently available, so abort the resync
1188 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001189 return;
1190 }
1191
Dan Stoza9e56aa02015-11-02 13:00:03 -08001192 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1193 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194
1195 mPrimaryDispSync.reset();
1196 mPrimaryDispSync.setPeriod(period);
1197
1198 if (!mPrimaryHWVsyncEnabled) {
1199 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001200 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1201 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001202 mPrimaryHWVsyncEnabled = true;
1203 }
1204}
1205
Jesse Hall948fe0c2013-10-14 12:56:09 -07001206void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001207 Mutex::Autolock _l(mHWVsyncLock);
1208 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001209 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1210 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001211 mPrimaryDispSync.endResync();
1212 mPrimaryHWVsyncEnabled = false;
1213 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001214 if (makeUnavailable) {
1215 mHWVsyncAvailable = false;
1216 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217}
1218
Tim Murray4a4e4a22016-04-19 16:29:23 +00001219void SurfaceFlinger::resyncWithRateLimit() {
1220 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001221
1222 // No explicit locking is needed here since EventThread holds a lock while calling this method
1223 static nsecs_t sLastResyncAttempted = 0;
1224 const nsecs_t now = systemTime();
1225 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001226 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001227 }
Dan Stoza57164302017-05-08 14:03:54 -07001228 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001229}
1230
Steven Thomasb02664d2017-07-26 18:48:28 -07001231void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1232 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001233 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001234 // Ignore any vsyncs from a previous hardware composer.
1235 if (sequenceId != mComposerSequenceId) {
1236 return;
1237 }
1238
1239 int32_t type;
1240 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001241 return;
1242 }
1243
Jamie Gennisd1700752013-10-14 12:22:52 -07001244 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245
Jamie Gennisd1700752013-10-14 12:22:52 -07001246 { // Scope for the lock
1247 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001248 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001249 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001250 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001251 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001252
1253 if (needsHwVsync) {
1254 enableHardwareVsync();
1255 } else {
1256 disableHardwareVsync(false);
1257 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001258}
1259
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001260void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001261 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001262 *compositorTiming = mCompositorTiming;
1263}
1264
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001265void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001266 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001267 wp<IBinder> token = mBuiltinDisplays[type];
1268
1269 // All non-virtual displays are currently considered secure.
1270 const bool isSecure = true;
1271
1272 sp<IGraphicBufferProducer> producer;
1273 sp<IGraphicBufferConsumer> consumer;
1274 BufferQueue::createBufferQueue(&producer, &consumer);
1275
1276 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1277
1278 bool hasWideColorModes = false;
1279 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1280 for (android_color_mode_t colorMode : modes) {
1281 switch (colorMode) {
1282 case HAL_COLOR_MODE_DISPLAY_P3:
1283 case HAL_COLOR_MODE_ADOBE_RGB:
1284 case HAL_COLOR_MODE_DCI_P3:
1285 hasWideColorModes = true;
1286 break;
1287 default:
1288 break;
1289 }
1290 }
1291 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1292 token, fbs, producer, mRenderEngine->getEGLConfig(),
1293 hasWideColorModes && hasWideColorDisplay);
1294 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001295 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1296 if (hasWideColorModes && hasWideColorDisplay) {
1297 defaultColorMode = HAL_COLOR_MODE_SRGB;
1298 }
1299 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001300 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001301
1302 // Add the primary display token to mDrawingState so we don't try to
1303 // recreate the DisplayDevice for the primary display.
1304 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1305
1306 // make the GLContext current so that we can create textures when creating
1307 // Layers (which may happens before we render something)
1308 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001309}
1310
Steven Thomasb02664d2017-07-26 18:48:28 -07001311void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1312 hwc2_display_t display, HWC2::Connection connection,
1313 bool primaryDisplay) {
1314 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1315 sequenceId, display,
1316 connection == HWC2::Connection::Connected ?
1317 "connected" : "disconnected",
1318 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001319
Steven Thomasb02664d2017-07-26 18:48:28 -07001320 // Only lock if we're not on the main thread. This function is normally
1321 // called on a hwbinder thread, but for the primary display it's called on
1322 // the main thread with the state lock already held, so don't attempt to
1323 // acquire it here.
1324 ConditionalLock lock(mStateLock,
1325 std::this_thread::get_id() != mMainThreadId);
1326
1327 if (primaryDisplay) {
1328 mHwc->onHotplug(display, connection);
1329 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1330 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001331 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001332 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001333 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001334 if (sequenceId != mComposerSequenceId) {
1335 return;
1336 }
1337 if (mHwc->isUsingVrComposer()) {
1338 ALOGE("External displays are not supported by the vr hardware composer.");
1339 return;
1340 }
1341 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001342 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001344 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001345 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001346 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1347 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001348 }
1349 setTransactionFlags(eDisplayTransactionNeeded);
1350
Andy McFadden9e9689c2012-10-10 18:17:51 -07001351 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001352 }
Mathias Agopian86303202012-07-24 22:46:10 -07001353}
1354
Steven Thomasb02664d2017-07-26 18:48:28 -07001355void SurfaceFlinger::onRefreshReceived(int sequenceId,
1356 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001357 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 if (sequenceId != mComposerSequenceId) {
1359 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001360 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001361 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001362}
1363
Dan Stoza9e56aa02015-11-02 13:00:03 -08001364void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001365 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001366 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001367 getHwComposer().setVsyncEnabled(disp,
1368 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001369}
1370
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001371// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001372void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001373 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001374 // Clear the drawing state so that the logic inside of
1375 // handleTransactionLocked will fire. It will determine the delta between
1376 // mCurrentState and mDrawingState and re-apply all changes when we make the
1377 // transition.
1378 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001380 mDisplays.clear();
1381}
1382
Steven Thomas050b2c82017-03-06 11:45:16 -08001383void SurfaceFlinger::updateVrFlinger() {
1384 if (!mVrFlinger)
1385 return;
1386 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1387 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001388 return;
1389 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001390
Steven Thomasb02664d2017-07-26 18:48:28 -07001391 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1392 ALOGE("Vr flinger is only supported for remote hardware composer"
1393 " service connections. Ignoring request to transition to vr"
1394 " flinger.");
1395 mVrFlingerRequestsDisplay = false;
1396 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001397 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001398
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001400
Steven Thomasb02664d2017-07-26 18:48:28 -07001401 int currentDisplayPowerMode = getDisplayDeviceLocked(
1402 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403
Steven Thomasb02664d2017-07-26 18:48:28 -07001404 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001405 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001406 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 resetDisplayState();
1409 mHwc.reset(); // Delete the current instance before creating the new one
1410 mHwc.reset(new HWComposer(
1411 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1412 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001413
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1415 "Switched to non-remote hardware composer");
1416
1417 if (vrFlingerRequestsDisplay) {
1418 mVrFlinger->GrantDisplayOwnership();
1419 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001421 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001422
1423 mVisibleRegionsDirty = true;
1424 invalidateHwcGeometry();
1425
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001426 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1428 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1429 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001430
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 // Reset the timing values to account for the period of the swapped in HWC
1432 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1433 const nsecs_t period = activeConfig->getVsyncPeriod();
1434 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001435
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 // Use phase of 0 since phase is not known.
1437 // Use latency of 0, which will snap to the ideal latency.
1438 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001439
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001440 android_atomic_or(1, &mRepaintEverything);
1441 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001442}
1443
Mathias Agopian4fec8732012-06-29 14:12:52 -07001444void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001445 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001446 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001447 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001448 bool frameMissed = !mHadClientComposition &&
1449 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001450 (mPreviousPresentFence->getSignalTime() ==
1451 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001452 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001453 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001454 signalLayerUpdate();
1455 break;
1456 }
1457
Steven Thomas050b2c82017-03-06 11:45:16 -08001458 // Now that we're going to make it to the handleMessageTransaction()
1459 // call below it's safe to call updateVrFlinger(), which will
1460 // potentially trigger a display handoff.
1461 updateVrFlinger();
1462
Dan Stoza6b9454d2014-11-07 16:00:59 -08001463 bool refreshNeeded = handleMessageTransaction();
1464 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001465 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001467 // Signal a refresh if a transaction modified the window state,
1468 // a new buffer was latched, or if HWC has requested a full
1469 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001470 signalRefresh();
1471 }
1472 break;
1473 }
1474 case MessageQueue::REFRESH: {
1475 handleMessageRefresh();
1476 break;
1477 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001478 }
1479}
1480
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001482 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001483 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001484 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001485 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001486 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001487 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001488}
1489
Dan Stoza6b9454d2014-11-07 16:00:59 -08001490bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001491 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001492 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001493}
1494
1495void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001496 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001497
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001498 mRefreshPending = false;
1499
Pablo Ceballos40845df2016-01-25 17:41:15 -08001500 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001501
Brian Andersond6927fb2016-07-23 23:37:30 -07001502 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001503 rebuildLayerStacks();
1504 setUpHWComposer();
1505 doDebugFlashRegions();
1506 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001507 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001508
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001509 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001510
1511 mHadClientComposition = false;
1512 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1513 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1514 mHadClientComposition = mHadClientComposition ||
1515 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1516 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001517
Dan Stoza9e56aa02015-11-02 13:00:03 -08001518 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001520
Mathias Agopiancd60f992012-08-16 16:28:27 -07001521void SurfaceFlinger::doDebugFlashRegions()
1522{
1523 // is debugging enabled
1524 if (CC_LIKELY(!mDebugRegion))
1525 return;
1526
1527 const bool repaintEverything = mRepaintEverything;
1528 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1529 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001530 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001531 // transform the dirty region into this screen's coordinate space
1532 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1533 if (!dirtyRegion.isEmpty()) {
1534 // redraw the whole screen
1535 doComposeSurfaces(hw, Region(hw->bounds()));
1536
1537 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001538 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001539 RenderEngine& engine(getRenderEngine());
1540 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1541
Mathias Agopianda27af92012-09-13 18:17:13 -07001542 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001543 }
1544 }
1545 }
1546
1547 postFramebuffer();
1548
1549 if (mDebugRegion > 1) {
1550 usleep(mDebugRegion * 1000);
1551 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001552
Dan Stoza9e56aa02015-11-02 13:00:03 -08001553 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001554 auto& displayDevice = mDisplays[displayId];
1555 if (!displayDevice->isDisplayOn()) {
1556 continue;
1557 }
1558
1559 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001560 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1561 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001562 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001563}
1564
Brian Andersond6927fb2016-07-23 23:37:30 -07001565void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001567 ATRACE_CALL();
1568 ALOGV("preComposition");
1569
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001571 mDrawingState.traverseInZOrder([&](Layer* layer) {
1572 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001573 needExtraInvalidate = true;
1574 }
Robert Carr2047fae2016-11-28 14:09:09 -08001575 });
1576
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577 if (needExtraInvalidate) {
1578 signalLayerUpdate();
1579 }
1580}
1581
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001582void SurfaceFlinger::updateCompositorTiming(
1583 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1584 std::shared_ptr<FenceTime>& presentFenceTime) {
1585 // Update queue of past composite+present times and determine the
1586 // most recently known composite to present latency.
1587 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1588 nsecs_t compositeToPresentLatency = -1;
1589 while (!mCompositePresentTimes.empty()) {
1590 CompositePresentTime& cpt = mCompositePresentTimes.front();
1591 // Cached values should have been updated before calling this method,
1592 // which helps avoid duplicate syscalls.
1593 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1594 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1595 break;
1596 }
1597 compositeToPresentLatency = displayTime - cpt.composite;
1598 mCompositePresentTimes.pop();
1599 }
1600
1601 // Don't let mCompositePresentTimes grow unbounded, just in case.
1602 while (mCompositePresentTimes.size() > 16) {
1603 mCompositePresentTimes.pop();
1604 }
1605
Brian Andersond0010582017-03-07 13:20:31 -08001606 setCompositorTimingSnapped(
1607 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1608}
1609
1610void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1611 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001612 // Integer division and modulo round toward 0 not -inf, so we need to
1613 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001614 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001615 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1616 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1617
Brian Andersond0010582017-03-07 13:20:31 -08001618 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1619 if (idealLatency <= 0) {
1620 idealLatency = vsyncInterval;
1621 }
1622
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001623 // Snap the latency to a value that removes scheduling jitter from the
1624 // composition and present times, which often have >1ms of jitter.
1625 // Reducing jitter is important if an app attempts to extrapolate
1626 // something (such as user input) to an accurate diasplay time.
1627 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1628 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001629 nsecs_t bias = vsyncInterval / 2;
1630 int64_t extraVsyncs =
1631 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1632 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1633 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634
Brian Andersond0010582017-03-07 13:20:31 -08001635 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001636 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1637 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001638 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001639}
1640
1641void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001642{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001643 ATRACE_CALL();
1644 ALOGV("postComposition");
1645
Brian Anderson3546a3f2016-07-14 11:51:14 -07001646 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001647 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001648 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001649 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001650 }
1651
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001652 // |mStateLock| not needed as we are on the main thread
1653 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001654
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001655 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001656 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1657 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1658 glCompositionDoneFenceTime =
1659 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1660 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1661 } else {
1662 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1663 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001664
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001665 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001666 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1667 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1668 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001669
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001670 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1671 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1672
1673 // We use the refreshStartTime which might be sampled a little later than
1674 // when we started doing work for this frame, but that should be okay
1675 // since updateCompositorTiming has snapping logic.
1676 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001677 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001678 CompositorTiming compositorTiming;
1679 {
1680 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1681 compositorTiming = mCompositorTiming;
1682 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001683
Robert Carr2047fae2016-11-28 14:09:09 -08001684 mDrawingState.traverseInZOrder([&](Layer* layer) {
1685 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001686 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001687 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001688 recordBufferingStats(layer->getName().string(),
1689 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001690 }
Robert Carr2047fae2016-11-28 14:09:09 -08001691 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001692
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001693 if (presentFenceTime->isValid()) {
1694 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001695 enableHardwareVsync();
1696 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001697 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001698 }
1699 }
1700
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001701 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001702 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001703 enableHardwareVsync();
1704 }
1705 }
1706
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001707 if (mAnimCompositionPending) {
1708 mAnimCompositionPending = false;
1709
Brian Anderson4e606e32017-03-16 15:34:57 -07001710 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001711 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001712 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001713 } else {
1714 // The HWC doesn't support present fences, so use the refresh
1715 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001716 nsecs_t presentTime =
1717 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001718 mAnimFrameTracker.setActualPresentTime(presentTime);
1719 }
1720 mAnimFrameTracker.advanceFrame();
1721 }
Dan Stozab90cf072015-03-05 11:05:59 -08001722
1723 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1724 return;
1725 }
1726
1727 nsecs_t currentTime = systemTime();
1728 if (mHasPoweredOff) {
1729 mHasPoweredOff = false;
1730 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001731 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001732 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001733 if (numPeriods < NUM_BUCKETS - 1) {
1734 mFrameBuckets[numPeriods] += elapsedTime;
1735 } else {
1736 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1737 }
1738 mTotalTime += elapsedTime;
1739 }
1740 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001741}
1742
1743void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001744 ATRACE_CALL();
1745 ALOGV("rebuildLayerStacks");
1746
Mathias Agopiancd60f992012-08-16 16:28:27 -07001747 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001748 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1749 ATRACE_CALL();
1750 mVisibleRegionsDirty = false;
1751 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001752
Jeff Sharkey76488112017-02-27 14:15:18 -07001753 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1754 Region opaqueRegion;
1755 Region dirtyRegion;
1756 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001757 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001758 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1759 const Transform& tr(displayDevice->getTransform());
1760 const Rect bounds(displayDevice->getBounds());
1761 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001762 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001763
Jeff Sharkey76488112017-02-27 14:15:18 -07001764 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001765 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001766 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1767 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001768 Region drawRegion(tr.transform(
1769 layer->visibleNonTransparentRegion));
1770 drawRegion.andSelf(bounds);
1771 if (!drawRegion.isEmpty()) {
1772 layersSortedByZ.add(layer);
1773 } else {
1774 // Clear out the HWC layer if this layer was
1775 // previously visible, but no longer is
Chia-I Wu92257612017-11-20 10:43:41 -08001776 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001777 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001778 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001779 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001780 // WM changes displayDevice->layerStack upon sleep/awake.
1781 // Here we make sure we delete the HWC layers even if
1782 // WM changed their layer stack.
Chia-I Wu92257612017-11-20 10:43:41 -08001783 hwcLayerDestroyed = layer->destroyHwcLayer(
1784 displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001785 }
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001786
1787 // If a layer is not going to get a release fence because
1788 // it is invisible, but it is also going to release its
1789 // old buffer, add it to the list of layers needing
1790 // fences.
1791 if (hwcLayerDestroyed) {
1792 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1793 mLayersWithQueuedFrames.cend(), layer);
1794 if (found != mLayersWithQueuedFrames.cend()) {
1795 layersNeedingFences.add(layer);
1796 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001797 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001798 });
1799 }
1800 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001801 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001802 displayDevice->undefinedRegion.set(bounds);
1803 displayDevice->undefinedRegion.subtractSelf(
1804 tr.transform(opaqueRegion));
1805 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001806 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001807 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001808}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001809
Romain Guy0147a172017-06-01 13:53:56 -07001810mat4 SurfaceFlinger::computeSaturationMatrix() const {
1811 if (mSaturation == 1.0f) {
1812 return mat4();
1813 }
1814
1815 // Rec.709 luma coefficients
1816 float3 luminance{0.213f, 0.715f, 0.072f};
1817 luminance *= 1.0f - mSaturation;
1818 return mat4(
1819 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1820 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1821 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1822 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1823 );
1824}
1825
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001826// pickColorMode translates a given dataspace into the best available color mode.
1827// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001828android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001829 switch (dataSpace) {
1830 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1831 // system expects.
1832 case HAL_DATASPACE_UNKNOWN:
1833 case HAL_DATASPACE_SRGB:
1834 case HAL_DATASPACE_V0_SRGB:
1835 return HAL_COLOR_MODE_SRGB;
1836 break;
1837
1838 case HAL_DATASPACE_DISPLAY_P3:
1839 return HAL_COLOR_MODE_DISPLAY_P3;
1840 break;
1841
1842 default:
1843 // TODO (courtneygo): Do we want to assert an error here?
1844 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1845 dataSpace);
1846 return HAL_COLOR_MODE_SRGB;
1847 break;
1848 }
1849}
1850
Romain Guy0147a172017-06-01 13:53:56 -07001851android_dataspace SurfaceFlinger::bestTargetDataSpace(
1852 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001853 // Only support sRGB and Display-P3 right now.
1854 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1855 return HAL_DATASPACE_DISPLAY_P3;
1856 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001857 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1858 return HAL_DATASPACE_DISPLAY_P3;
1859 }
1860 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1861 return HAL_DATASPACE_DISPLAY_P3;
1862 }
1863
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001864 return HAL_DATASPACE_V0_SRGB;
1865}
1866
Mathias Agopiancd60f992012-08-16 16:28:27 -07001867void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001868 ATRACE_CALL();
1869 ALOGV("setUpHWComposer");
1870
Jesse Hall028dc8f2013-08-20 16:35:32 -07001871 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001872 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1873 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1874 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1875
1876 // If nothing has changed (!dirty), don't recompose.
1877 // If something changed, but we don't currently have any visible layers,
1878 // and didn't when we last did a composition, then skip it this time.
1879 // The second rule does two things:
1880 // - When all layers are removed from a display, we'll emit one black
1881 // frame, then nothing more until we get new layers.
1882 // - When a display is created with a private layer stack, we won't
1883 // emit any black frames until a layer is added to the layer stack.
1884 bool mustRecompose = dirty && !(empty && wasEmpty);
1885
1886 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1887 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1888 mustRecompose ? "doing" : "skipping",
1889 dirty ? "+" : "-",
1890 empty ? "+" : "-",
1891 wasEmpty ? "+" : "-");
1892
Dan Stoza71433162014-02-04 16:22:36 -08001893 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001894
1895 if (mustRecompose) {
1896 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1897 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001898 }
1899
Dan Stoza9e56aa02015-11-02 13:00:03 -08001900 // build the h/w work list
1901 if (CC_UNLIKELY(mGeometryInvalid)) {
1902 mGeometryInvalid = false;
1903 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1904 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1905 const auto hwcId = displayDevice->getHwcDisplayId();
1906 if (hwcId >= 0) {
1907 const Vector<sp<Layer>>& currentLayers(
1908 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001909 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001910 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001911 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001912 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001913 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001915 }
1916 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001917
Robert Carrae060832016-11-28 10:51:00 -08001918 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001919 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001920 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001921 }
1922 }
1923 }
1924 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 }
Riley Andrews03414a12014-07-01 14:22:59 -07001926
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001927
Romain Guy0147a172017-06-01 13:53:56 -07001928 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001929
Dan Stoza9e56aa02015-11-02 13:00:03 -08001930 // Set the per-frame data
1931 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1932 auto& displayDevice = mDisplays[displayId];
1933 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001934
Dan Stoza9e56aa02015-11-02 13:00:03 -08001935 if (hwcId < 0) {
1936 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001937 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001938 if (colorMatrix != mPreviousColorMatrix) {
1939 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1940 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1941 "display %zd: %d", displayId, result);
1942 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001943 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1944 layer->setPerFrameData(displayDevice);
1945 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001946
1947 if (hasWideColorDisplay) {
1948 android_color_mode newColorMode;
1949 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1950
1951 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1952 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1953 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1954 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1955 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1956 }
1957 newColorMode = pickColorMode(newDataSpace);
1958
Thierry Strudel2924d012017-08-14 15:19:37 -07001959 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001960 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 }
1962
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001963 mPreviousColorMatrix = colorMatrix;
1964
Dan Stoza9e56aa02015-11-02 13:00:03 -08001965 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001966 auto& displayDevice = mDisplays[displayId];
1967 if (!displayDevice->isDisplayOn()) {
1968 continue;
1969 }
1970
1971 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001972 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1973 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001974 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001975}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001976
Mathias Agopiancd60f992012-08-16 16:28:27 -07001977void SurfaceFlinger::doComposition() {
1978 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001979 ALOGV("doComposition");
1980
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001981 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001982 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001983 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001984 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001985 // transform the dirty region into this screen's coordinate space
1986 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001987
1988 // repaint the framebuffer (if needed)
1989 doDisplayComposition(hw, dirtyRegion);
1990
Mathias Agopiancd60f992012-08-16 16:28:27 -07001991 hw->dirtyRegion.clear();
1992 hw->flip(hw->swapRegion);
1993 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001994 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001995 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001996 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001997}
1998
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001999void SurfaceFlinger::postFramebuffer()
2000{
Mathias Agopian841cde52012-03-01 15:44:37 -08002001 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002003
Mathias Agopiana44b0412011-10-16 18:46:35 -07002004 const nsecs_t now = systemTime();
2005 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002006
Dan Stoza9e56aa02015-11-02 13:00:03 -08002007 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2008 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002009 if (!displayDevice->isDisplayOn()) {
2010 continue;
2011 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 const auto hwcId = displayDevice->getHwcDisplayId();
2013 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002014 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002015 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002016 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002017 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002019 // The layer buffer from the previous frame (if any) is released
2020 // by HWC only when the release fence from this frame (if any) is
2021 // signaled. Always get the release fence from HWC first.
2022 auto hwcLayer = layer->getHwcLayer(hwcId);
2023 sp<Fence> releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2024
2025 // If the layer was client composited in the previous frame, we
2026 // need to merge with the previous client target acquire fence.
2027 // Since we do not track that, always merge with the current
2028 // client target acquire fence when it is available, even though
2029 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002030 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002031 releaseFence = Fence::merge("LayerRelease", releaseFence,
2032 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002033 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002034
Dan Stoza9e56aa02015-11-02 13:00:03 -08002035 layer->onLayerDisplayed(releaseFence);
2036 }
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08002037
2038 // We've got a list of layers needing fences, that are disjoint with
2039 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2040 // supply them with the present fence.
2041 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
2042 sp<Fence> presentFence = mHwc->getPresentFence(hwcId);
2043 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2044 layer->onLayerDisplayed(presentFence);
2045 }
2046 }
2047
Dan Stoza9e56aa02015-11-02 13:00:03 -08002048 if (hwcId >= 0) {
2049 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002050 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002051 }
2052
Mathias Agopiana44b0412011-10-16 18:46:35 -07002053 mLastSwapBufferTime = systemTime() - now;
2054 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002055
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002056 // |mStateLock| not needed as we are on the main thread
2057 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002058 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2059 logFrameStats();
2060 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002061}
2062
Mathias Agopian87baae12012-07-31 12:38:26 -07002063void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002064{
Mathias Agopian841cde52012-03-01 15:44:37 -08002065 ATRACE_CALL();
2066
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002067 // here we keep a copy of the drawing state (that is the state that's
2068 // going to be overwritten by handleTransactionLocked()) outside of
2069 // mStateLock so that the side-effects of the State assignment
2070 // don't happen with mStateLock held (which can cause deadlocks).
2071 State drawingState(mDrawingState);
2072
Mathias Agopianca4d3602011-05-19 15:38:14 -07002073 Mutex::Autolock _l(mStateLock);
2074 const nsecs_t now = systemTime();
2075 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002076
Mathias Agopianca4d3602011-05-19 15:38:14 -07002077 // Here we're guaranteed that some transaction flags are set
2078 // so we can call handleTransactionLocked() unconditionally.
2079 // We call getTransactionFlags(), which will also clear the flags,
2080 // with mStateLock held to guarantee that mCurrentState won't change
2081 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002082
Mathias Agopiane57f2922012-08-09 16:29:12 -07002083 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002084 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002085
Mathias Agopianca4d3602011-05-19 15:38:14 -07002086 mLastTransactionTime = systemTime() - now;
2087 mDebugInTransaction = 0;
2088 invalidateHwcGeometry();
2089 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002090}
2091
Mathias Agopian87baae12012-07-31 12:38:26 -07002092void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002093{
Dan Stoza7dde5992015-05-22 09:51:44 -07002094 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002095 mCurrentState.traverseInZOrder([](Layer* layer) {
2096 layer->notifyAvailableFrames();
2097 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002098
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002099 /*
2100 * Traversal of the children
2101 * (perform the transaction for each of them if needed)
2102 */
2103
Mathias Agopian3559b072012-08-15 13:46:03 -07002104 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002105 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002106 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002107 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002108
2109 const uint32_t flags = layer->doTransaction(0);
2110 if (flags & Layer::eVisibleRegion)
2111 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002112 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002113 }
2114
2115 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002116 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002117 */
2118
Mathias Agopiane57f2922012-08-09 16:29:12 -07002119 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002120 // here we take advantage of Vector's copy-on-write semantics to
2121 // improve performance by skipping the transaction entirely when
2122 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002123 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2124 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002125 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002126 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002127 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002128 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002129
2130 // find the displays that were removed
2131 // (ie: in drawing state but not in current state)
2132 // also handle displays that changed
2133 // (ie: displays that are in both lists)
Ivan Lozano34ff8782017-12-06 17:07:27 -08002134 for (size_t i=0 ; i<dc ;) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002135 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2136 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002137 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002138 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002139 // Call makeCurrent() on the primary display so we can
2140 // be sure that nothing associated with this display
2141 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002142 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002143 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002144 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002145 if (hw != NULL)
2146 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002147 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002148 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002149 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002150 } else {
2151 ALOGW("trying to remove the main display");
2152 }
2153 } else {
2154 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002155 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002156 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002157 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2158 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002159 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002160 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002161 // recreating the DisplayDevice, so we just remove it
2162 // from the drawing state, so that it get re-added
2163 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002164 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002165 if (hw != NULL)
2166 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002167 mDisplays.removeItem(display);
2168 mDrawingState.displays.removeItemsAt(i);
Ivan Lozano34ff8782017-12-06 17:07:27 -08002169 dc--;
Mathias Agopian93997a82012-08-29 17:30:36 -07002170 // at this point we must loop to the next item
2171 continue;
2172 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002173
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002174 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002175 if (disp != NULL) {
2176 if (state.layerStack != draw[i].layerStack) {
2177 disp->setLayerStack(state.layerStack);
2178 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002179 if ((state.orientation != draw[i].orientation)
2180 || (state.viewport != draw[i].viewport)
2181 || (state.frame != draw[i].frame))
2182 {
2183 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002184 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002185 }
Michael Lentine47e45402014-07-18 15:34:25 -07002186 if (state.width != draw[i].width || state.height != draw[i].height) {
2187 disp->setDisplaySize(state.width, state.height);
2188 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002189 }
2190 }
Ivan Lozano34ff8782017-12-06 17:07:27 -08002191 ++i;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002192 }
2193
2194 // find displays that were added
2195 // (ie: in current state but not in drawing state)
2196 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002197 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002198 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002199
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002200 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002201 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002202 sp<IGraphicBufferProducer> bqProducer;
2203 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002204 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002205
Dan Stoza9e56aa02015-11-02 13:00:03 -08002206 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002207 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002208 // Virtual displays without a surface are dormant:
2209 // they have external state (layer stack, projection,
2210 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002211 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002212
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002213 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002214 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002215 int width = 0;
2216 int status = state.surface->query(
2217 NATIVE_WINDOW_WIDTH, &width);
2218 ALOGE_IF(status != NO_ERROR,
2219 "Unable to query width (%d)", status);
2220 int height = 0;
2221 status = state.surface->query(
2222 NATIVE_WINDOW_HEIGHT, &height);
2223 ALOGE_IF(status != NO_ERROR,
2224 "Unable to query height (%d)", status);
2225 int intFormat = 0;
2226 status = state.surface->query(
2227 NATIVE_WINDOW_FORMAT, &intFormat);
2228 ALOGE_IF(status != NO_ERROR,
2229 "Unable to query format (%d)", status);
2230 auto format = static_cast<android_pixel_format_t>(
2231 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002232
Dan Stoza8cf150a2016-08-02 10:27:31 -07002233 mHwc->allocateVirtualDisplay(width, height, &format,
2234 &hwcId);
2235 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002236
Dan Stoza5cf424b2016-05-20 14:02:39 -07002237 // TODO: Plumb requested format back up to consumer
2238
Dan Stoza9e56aa02015-11-02 13:00:03 -08002239 sp<VirtualDisplaySurface> vds =
2240 new VirtualDisplaySurface(*mHwc,
2241 hwcId, state.surface, bqProducer,
2242 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002243
2244 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002245 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002246 }
2247 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002248 ALOGE_IF(state.surface!=NULL,
2249 "adding a supported display, but rendering "
2250 "surface is provided (%p), ignoring it",
2251 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002252
2253 hwcId = state.type;
2254 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2255 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002256 }
2257
2258 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002259 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002260 sp<DisplayDevice> hw =
2261 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2262 dispSurface, producer,
2263 mRenderEngine->getEGLConfig(),
2264 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002265 hw->setLayerStack(state.layerStack);
2266 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002267 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002268 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002269 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002270 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002271 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002272 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002273 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002274 }
2275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002276 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002277 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002278
Mathias Agopian84300952012-11-21 16:02:13 -08002279 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2280 // The transform hint might have changed for some layers
2281 // (either because a display has changed, or because a layer
2282 // as changed).
2283 //
2284 // Walk through all the layers in currentLayers,
2285 // and update their transform hint.
2286 //
2287 // If a layer is visible only on a single display, then that
2288 // display is used to calculate the hint, otherwise we use the
2289 // default display.
2290 //
2291 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2292 // the hint is set before we acquire a buffer from the surface texture.
2293 //
2294 // NOTE: layer transactions have taken place already, so we use their
2295 // drawing state. However, SurfaceFlinger's own transaction has not
2296 // happened yet, so we must use the current state layer list
2297 // (soon to become the drawing state list).
2298 //
2299 sp<const DisplayDevice> disp;
2300 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002301 bool first = true;
2302 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002303 // NOTE: we rely on the fact that layers are sorted by
2304 // layerStack first (so we don't have to traverse the list
2305 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002306 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002307 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002308 currentlayerStack = layerStack;
2309 // figure out if this layerstack is mirrored
2310 // (more than one display) if so, pick the default display,
2311 // if not, pick the only display it's on.
2312 disp.clear();
2313 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2314 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002315 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002316 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002317 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002318 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002319 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002320 break;
2321 }
2322 }
2323 }
2324 }
Chet Haase91d25932013-04-11 15:24:55 -07002325 if (disp == NULL) {
2326 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2327 // redraw after transform hint changes. See bug 8508397.
2328
2329 // could be null when this layer is using a layerStack
2330 // that is not visible on any display. Also can occur at
2331 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002332 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002333 }
Chet Haase91d25932013-04-11 15:24:55 -07002334 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002335
2336 first = false;
2337 });
Mathias Agopian84300952012-11-21 16:02:13 -08002338 }
2339
2340
Mathias Agopian3559b072012-08-15 13:46:03 -07002341 /*
2342 * Perform our own transaction if needed
2343 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002344
2345 if (mLayersAdded) {
2346 mLayersAdded = false;
2347 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002348 mVisibleRegionsDirty = true;
2349 }
2350
2351 // some layers might have been removed, so
2352 // we need to update the regions they're exposing.
2353 if (mLayersRemoved) {
2354 mLayersRemoved = false;
2355 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002356 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002357 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002358 // this layer is not visible anymore
2359 // TODO: we could traverse the tree from front to back and
2360 // compute the actual visible region
2361 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002362 Region visibleReg;
2363 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002364 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002365 }
Robert Carr2047fae2016-11-28 14:09:09 -08002366 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367 }
2368
2369 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002370
2371 updateCursorAsync();
2372}
2373
2374void SurfaceFlinger::updateCursorAsync()
2375{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002376 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2377 auto& displayDevice = mDisplays[displayId];
2378 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002379 continue;
2380 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002381
2382 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2383 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002384 }
2385 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002386}
2387
2388void SurfaceFlinger::commitTransaction()
2389{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002390 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002391 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002392 for (const auto& l : mLayersPendingRemoval) {
2393 recordBufferingStats(l->getName().string(),
2394 l->getOccupancyHistory(true));
2395 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002396 }
2397 mLayersPendingRemoval.clear();
2398 }
2399
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002400 // If this transaction is part of a window animation then the next frame
2401 // we composite should be considered an animation as well.
2402 mAnimCompositionPending = mAnimTransactionPending;
2403
Mathias Agopian4fec8732012-06-29 14:12:52 -07002404 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002405 mDrawingState.traverseInZOrder([](Layer* layer) {
2406 layer->commitChildList();
2407 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002408 mTransactionPending = false;
2409 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002410 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002411}
2412
Chia-I Wuab0c3192017-08-01 11:29:00 -07002413void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002414 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002415{
Mathias Agopian841cde52012-03-01 15:44:37 -08002416 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002417 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002418
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002419 Region aboveOpaqueLayers;
2420 Region aboveCoveredLayers;
2421 Region dirty;
2422
Mathias Agopian87baae12012-07-31 12:38:26 -07002423 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002424
Robert Carr2047fae2016-11-28 14:09:09 -08002425 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002426 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002427 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002428
Jesse Hall01e29052013-02-19 16:13:35 -08002429 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002430 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002431 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002432
Mathias Agopianab028732010-03-16 16:41:46 -07002433 /*
2434 * opaqueRegion: area of a surface that is fully opaque.
2435 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002436 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002437
2438 /*
2439 * visibleRegion: area of a surface that is visible on screen
2440 * and not fully transparent. This is essentially the layer's
2441 * footprint minus the opaque regions above it.
2442 * Areas covered by a translucent surface are considered visible.
2443 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002444 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002445
2446 /*
2447 * coveredRegion: area of a surface that is covered by all
2448 * visible regions above it (which includes the translucent areas).
2449 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002451
Jesse Halla8026d22012-09-25 13:25:04 -07002452 /*
2453 * transparentRegion: area of a surface that is hinted to be completely
2454 * transparent. This is only used to tell when the layer has no visible
2455 * non-transparent regions and can be removed from the layer list. It
2456 * does not affect the visibleRegion of this layer or any layers
2457 * beneath it. The hint may not be correct if apps don't respect the
2458 * SurfaceView restrictions (which, sadly, some don't).
2459 */
2460 Region transparentRegion;
2461
Mathias Agopianab028732010-03-16 16:41:46 -07002462
2463 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002464 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002465 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002466 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002468 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002469 if (!visibleRegion.isEmpty()) {
2470 // Remove the transparent area from the visible region
2471 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002472 if (tr.preserveRects()) {
2473 // transform the transparent region
2474 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002475 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002476 // transformation too complex, can't do the
2477 // transparent region optimization.
2478 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002479 }
Mathias Agopianab028732010-03-16 16:41:46 -07002480 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002481
Mathias Agopianab028732010-03-16 16:41:46 -07002482 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002483 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002484 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002485 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2486 // the opaque region is the layer's footprint
2487 opaqueRegion = visibleRegion;
2488 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489 }
2490 }
2491
Mathias Agopianab028732010-03-16 16:41:46 -07002492 // Clip the covered region to the visible region
2493 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2494
2495 // Update aboveCoveredLayers for next (lower) layer
2496 aboveCoveredLayers.orSelf(visibleRegion);
2497
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498 // subtract the opaque region covered by the layers above us
2499 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500
2501 // compute this layer's dirty region
2502 if (layer->contentDirty) {
2503 // we need to invalidate the whole region
2504 dirty = visibleRegion;
2505 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002506 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507 layer->contentDirty = false;
2508 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002509 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002510 * the exposed region consists of two components:
2511 * 1) what's VISIBLE now and was COVERED before
2512 * 2) what's EXPOSED now less what was EXPOSED before
2513 *
2514 * note that (1) is conservative, we start with the whole
2515 * visible region but only keep what used to be covered by
2516 * something -- which mean it may have been exposed.
2517 *
2518 * (2) handles areas that were not covered by anything but got
2519 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002520 */
Mathias Agopianab028732010-03-16 16:41:46 -07002521 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002522 const Region oldVisibleRegion = layer->visibleRegion;
2523 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002524 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2525 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526 }
2527 dirty.subtractSelf(aboveOpaqueLayers);
2528
2529 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002530 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002531
Mathias Agopianab028732010-03-16 16:41:46 -07002532 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002533 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002534
Jesse Halla8026d22012-09-25 13:25:04 -07002535 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536 layer->setVisibleRegion(visibleRegion);
2537 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002538 layer->setVisibleNonTransparentRegion(
2539 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002540 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541
Mathias Agopian87baae12012-07-31 12:38:26 -07002542 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543}
2544
Chia-I Wuab0c3192017-08-01 11:29:00 -07002545void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002546 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002547 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002548 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002549 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002550 }
2551 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002552}
2553
Dan Stoza6b9454d2014-11-07 16:00:59 -08002554bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002555{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002556 ALOGV("handlePageFlip");
2557
Brian Andersond6927fb2016-07-23 23:37:30 -07002558 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559
Mathias Agopian4fec8732012-06-29 14:12:52 -07002560 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002561 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002562 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002563
2564 // Store the set of layers that need updates. This set must not change as
2565 // buffers are being latched, as this could result in a deadlock.
2566 // Example: Two producers share the same command stream and:
2567 // 1.) Layer 0 is latched
2568 // 2.) Layer 0 gets a new frame
2569 // 2.) Layer 1 gets a new frame
2570 // 3.) Layer 1 is latched.
2571 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2572 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002573 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002574 if (layer->hasQueuedFrame()) {
2575 frameQueued = true;
2576 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002577 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002578 } else {
2579 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002580 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002581 } else {
2582 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002583 }
Robert Carr2047fae2016-11-28 14:09:09 -08002584 });
2585
Dan Stoza9e56aa02015-11-02 13:00:03 -08002586 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002587 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002588 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002589 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002590 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002591 newDataLatched = true;
2592 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002593 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002594
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002595 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002596
2597 // If we will need to wake up at some time in the future to deal with a
2598 // queued frame that shouldn't be displayed during this vsync period, wake
2599 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002600 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002601 signalLayerUpdate();
2602 }
2603
2604 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002605 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606}
2607
Mathias Agopianad456f92011-01-13 17:53:01 -08002608void SurfaceFlinger::invalidateHwcGeometry()
2609{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002610 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002611}
2612
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002613
Fabien Sanglard830b8472016-11-30 16:35:58 -08002614void SurfaceFlinger::doDisplayComposition(
2615 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002616 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002617{
Dan Stoza71433162014-02-04 16:22:36 -08002618 // We only need to actually compose the display if:
2619 // 1) It is being handled by hardware composer, which may need this to
2620 // keep its virtual display state machine in sync, or
2621 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002622 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002623 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002624 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002625 return;
2626 }
2627
Dan Stoza9e56aa02015-11-02 13:00:03 -08002628 ALOGV("doDisplayComposition");
2629
Mathias Agopian87baae12012-07-31 12:38:26 -07002630 Region dirtyRegion(inDirtyRegion);
2631
Mathias Agopianb8a55602009-06-26 19:06:36 -07002632 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002633 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634
Fabien Sanglard830b8472016-11-30 16:35:58 -08002635 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002636 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002637 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2638 // takes a rectangle, we must make sure to update that whole
2639 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002640 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002641 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002642 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002643 // We need to redraw the rectangle that will be updated
2644 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002645 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002646 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002647 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002648 } else {
2649 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002650 dirtyRegion.set(displayDevice->bounds());
2651 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652 }
2653 }
2654
Fabien Sanglard830b8472016-11-30 16:35:58 -08002655 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002657 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002658 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002659
2660 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002661 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662}
2663
Dan Stoza9e56aa02015-11-02 13:00:03 -08002664bool SurfaceFlinger::doComposeSurfaces(
2665 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002666{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002667 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002668
Dan Stoza9e56aa02015-11-02 13:00:03 -08002669 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002670
2671 mat4 oldColorMatrix;
2672 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2673 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2674 if (applyColorMatrix) {
2675 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2676 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2677 }
2678
Dan Stoza9e56aa02015-11-02 13:00:03 -08002679 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2680 if (hasClientComposition) {
2681 ALOGV("hasClientComposition");
2682
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002683#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002684 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002685 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002686#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002687 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002688 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002689 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002690 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002691
2692 // |mStateLock| not needed as we are on the main thread
2693 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002694 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2695 }
2696 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002697 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002698
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002699 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002700 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2701 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002702 // when using overlays, we assume a fully transparent framebuffer
2703 // NOTE: we could reduce how much we need to clear, for instance
2704 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002705 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002706 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002707 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002708 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002709 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002710 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002711
2712 // we remove the scissor part
2713 // we're left with the letterbox region
2714 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002715 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002716
2717 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002718 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002719
2720 // but limit it to the dirty region
2721 region.andSelf(dirty);
2722
Mathias Agopianb9494d52012-04-18 02:28:45 -07002723 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002724 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002725 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002726 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002727 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002728 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002729
Dan Stoza9e56aa02015-11-02 13:00:03 -08002730 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002731 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002732 // scissor on the main display. It should never be needed
2733 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002734 const Rect& bounds(displayDevice->getBounds());
2735 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002736 if (scissor != bounds) {
2737 // scissor doesn't match the screen's dimensions, so we
2738 // need to clear everything outside of it and enable
2739 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002740
Mathias Agopianf45c5102012-10-24 16:29:17 -07002741 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002742 const uint32_t height = displayDevice->getHeight();
2743 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002744 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002745 }
2746 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002747 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002748
Mathias Agopian85d751c2012-08-29 16:59:24 -07002749 /*
2750 * and then, render the layers targeted at the framebuffer
2751 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002752
Dan Stoza9e56aa02015-11-02 13:00:03 -08002753 ALOGV("Rendering client layers");
2754 const Transform& displayTransform = displayDevice->getTransform();
2755 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002756 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002757 bool firstLayer = true;
2758 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2759 const Region clip(dirty.intersect(
2760 displayTransform.transform(layer->visibleRegion)));
2761 ALOGV("Layer: %s", layer->getName().string());
2762 ALOGV(" Composition type: %s",
2763 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002764 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002765 switch (layer->getCompositionType(hwcId)) {
2766 case HWC2::Composition::Cursor:
2767 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002768 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002769 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002770 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2772 layer->isOpaque(state) && (state.alpha == 1.0f)
2773 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002774 // never clear the very first layer since we're
2775 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002776 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002777 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002778 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002779 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002780 case HWC2::Composition::Client: {
2781 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002782 break;
2783 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002784 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002785 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002786 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002787 } else {
2788 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002789 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002790 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002791 }
2792 } else {
2793 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002794 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002795 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002796 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002797 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002798 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002799 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002800 }
2801 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002802
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002803 if (applyColorMatrix) {
2804 getRenderEngine().setupColorTransform(oldColorMatrix);
2805 }
2806
Mathias Agopianf45c5102012-10-24 16:29:17 -07002807 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002808 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002809 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810}
2811
Fabien Sanglard830b8472016-11-30 16:35:58 -08002812void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2813 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002814 RenderEngine& engine(getRenderEngine());
2815 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002816}
2817
Dan Stoza7d89d062015-04-30 13:29:25 -07002818status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002819 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002820 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002821 const sp<Layer>& lbc,
2822 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002823{
Dan Stoza7d89d062015-04-30 13:29:25 -07002824 // add this layer to the current state list
2825 {
2826 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002827 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002828 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2829 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002830 return NO_MEMORY;
2831 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002832 if (parent == nullptr) {
2833 mCurrentState.layersSortedByZ.add(lbc);
2834 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002835 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2836 ALOGE("addClientLayer called with a removed parent");
2837 return NAME_NOT_FOUND;
2838 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002839 parent->addChild(lbc);
2840 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002841
Dan Stoza7d89d062015-04-30 13:29:25 -07002842 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002843 mLayersAdded = true;
2844 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002845 }
2846
Mathias Agopian96f08192010-06-02 23:28:45 -07002847 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002848 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002849
Dan Stoza7d89d062015-04-30 13:29:25 -07002850 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002851}
2852
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002853status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002854 Mutex::Autolock _l(mStateLock);
2855
Robert Carr1f0a16a2016-10-24 16:27:39 -07002856 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002857 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002858 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002859 if (topLevelOnly) {
2860 return NO_ERROR;
2861 }
2862
Chia-I Wu98f1c102017-05-30 14:54:08 -07002863 sp<Layer> ancestor = p;
2864 while (ancestor->getParent() != nullptr) {
2865 ancestor = ancestor->getParent();
2866 }
2867 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2868 ALOGE("removeLayer called with a layer whose parent has been removed");
2869 return NAME_NOT_FOUND;
2870 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002871
2872 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002873 } else {
2874 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002875 }
2876
Robert Carr136e2f62017-02-08 17:54:29 -08002877 // As a matter of normal operation, the LayerCleaner will produce a second
2878 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2879 // so we will succeed in promoting it, but it's already been removed
2880 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2881 // otherwise something has gone wrong and we are leaking the layer.
2882 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2884 layer->getName().string(),
2885 (p != nullptr) ? p->getName().string() : "no-parent");
2886 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002887 } else if (index < 0) {
2888 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002889 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002890
Chia-I Wuc6657022017-08-15 11:18:17 -07002891 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002892 mLayersPendingRemoval.add(layer);
2893 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002894 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002895 setTransactionFlags(eTransactionNeeded);
2896 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897}
2898
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002899uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002900 return android_atomic_release_load(&mTransactionFlags);
2901}
2902
Mathias Agopian3f844832013-08-07 21:24:32 -07002903uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2905}
2906
Mathias Agopian3f844832013-08-07 21:24:32 -07002907uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2909 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002910 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002911 }
2912 return old;
2913}
2914
Mathias Agopian8b33f032012-07-24 20:43:54 -07002915void SurfaceFlinger::setTransactionState(
2916 const Vector<ComposerState>& state,
2917 const Vector<DisplayState>& displays,
2918 uint32_t flags)
2919{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002920 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002921 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002922 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002923
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002924 if (flags & eAnimation) {
2925 // For window updates that are part of an animation we must wait for
2926 // previous animation "frames" to be handled.
2927 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002928 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002929 if (CC_UNLIKELY(err != NO_ERROR)) {
2930 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002931 // caller after a few seconds.
2932 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2933 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002934 mAnimTransactionPending = false;
2935 break;
2936 }
2937 }
2938 }
2939
Mathias Agopiane57f2922012-08-09 16:29:12 -07002940 size_t count = displays.size();
2941 for (size_t i=0 ; i<count ; i++) {
2942 const DisplayState& s(displays[i]);
2943 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002944 }
2945
Mathias Agopiane57f2922012-08-09 16:29:12 -07002946 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002947 for (size_t i=0 ; i<count ; i++) {
2948 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002949 // Here we need to check that the interface we're given is indeed
2950 // one of our own. A malicious client could give us a NULL
2951 // IInterface, or one of its own or even one of our own but a
2952 // different type. All these situations would cause us to crash.
2953 //
2954 // NOTE: it would be better to use RTTI as we could directly check
2955 // that we have a Client*. however, RTTI is disabled in Android.
2956 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002957 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002958 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002959 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002960 sp<Client> client( static_cast<Client *>(s.client.get()) );
2961 transactionFlags |= setClientStateLocked(client, s.state);
2962 }
2963 }
2964 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002965 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002966
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002967 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2968 // anyway. This can be used as a flush mechanism for previous async transactions.
2969 // Empty animation transaction can be used to simulate back-pressure, so also force a
2970 // transaction for empty animation transactions.
2971 if (transactionFlags == 0 &&
2972 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002973 transactionFlags = eTransactionNeeded;
2974 }
2975
Mathias Agopian386aa982011-11-07 21:58:03 -08002976 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002977 if (mInterceptor.isEnabled()) {
2978 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2979 }
Irvel468051e2016-06-13 16:44:44 -07002980
Mathias Agopian386aa982011-11-07 21:58:03 -08002981 // this triggers the transaction
2982 setTransactionFlags(transactionFlags);
2983
2984 // if this is a synchronous transaction, wait for it to take effect
2985 // before returning.
2986 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002987 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002988 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002989 if (flags & eAnimation) {
2990 mAnimTransactionPending = true;
2991 }
2992 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002993 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2994 if (CC_UNLIKELY(err != NO_ERROR)) {
2995 // just in case something goes wrong in SF, return to the
2996 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002997 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2998 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002999 break;
3000 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003001 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003002 }
3003}
3004
Mathias Agopiane57f2922012-08-09 16:29:12 -07003005uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3006{
Jesse Hall9a143922012-10-04 16:29:19 -07003007 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3008 if (dpyIdx < 0)
3009 return 0;
3010
Mathias Agopiane57f2922012-08-09 16:29:12 -07003011 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003012 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003013 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003014 const uint32_t what = s.what;
3015 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003016 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003017 disp.surface = s.surface;
3018 flags |= eDisplayTransactionNeeded;
3019 }
3020 }
3021 if (what & DisplayState::eLayerStackChanged) {
3022 if (disp.layerStack != s.layerStack) {
3023 disp.layerStack = s.layerStack;
3024 flags |= eDisplayTransactionNeeded;
3025 }
3026 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003027 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003028 if (disp.orientation != s.orientation) {
3029 disp.orientation = s.orientation;
3030 flags |= eDisplayTransactionNeeded;
3031 }
3032 if (disp.frame != s.frame) {
3033 disp.frame = s.frame;
3034 flags |= eDisplayTransactionNeeded;
3035 }
3036 if (disp.viewport != s.viewport) {
3037 disp.viewport = s.viewport;
3038 flags |= eDisplayTransactionNeeded;
3039 }
3040 }
Michael Lentine47e45402014-07-18 15:34:25 -07003041 if (what & DisplayState::eDisplaySizeChanged) {
3042 if (disp.width != s.width) {
3043 disp.width = s.width;
3044 flags |= eDisplayTransactionNeeded;
3045 }
3046 if (disp.height != s.height) {
3047 disp.height = s.height;
3048 flags |= eDisplayTransactionNeeded;
3049 }
3050 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003051 }
3052 return flags;
3053}
3054
3055uint32_t SurfaceFlinger::setClientStateLocked(
3056 const sp<Client>& client,
3057 const layer_state_t& s)
3058{
3059 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003060 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003061 if (layer != 0) {
3062 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003063 bool geometryAppliesWithResize =
3064 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003065 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003066 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003067 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003068 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003069 }
3070 if (what & layer_state_t::eLayerChanged) {
3071 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003072 const auto& p = layer->getParent();
3073 if (p == nullptr) {
3074 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3075 if (layer->setLayer(s.z) && idx >= 0) {
3076 mCurrentState.layersSortedByZ.removeAt(idx);
3077 mCurrentState.layersSortedByZ.add(layer);
3078 // we need traversal (state changed)
3079 // AND transaction (list changed)
3080 flags |= eTransactionNeeded|eTraversalNeeded;
3081 }
3082 } else {
3083 if (p->setChildLayer(layer, s.z)) {
3084 flags |= eTransactionNeeded|eTraversalNeeded;
3085 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003086 }
3087 }
Robert Carrdb66e622017-04-10 16:55:57 -07003088 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003089 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003090 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003091 mCurrentState.layersSortedByZ.removeAt(idx);
3092 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003093 flags |= eTransactionNeeded|eTraversalNeeded;
3094 }
3095 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003096 if (what & layer_state_t::eSizeChanged) {
3097 if (layer->setSize(s.w, s.h)) {
3098 flags |= eTraversalNeeded;
3099 }
3100 }
3101 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003102 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003103 flags |= eTraversalNeeded;
3104 }
3105 if (what & layer_state_t::eMatrixChanged) {
3106 if (layer->setMatrix(s.matrix))
3107 flags |= eTraversalNeeded;
3108 }
3109 if (what & layer_state_t::eTransparentRegionChanged) {
3110 if (layer->setTransparentRegionHint(s.transparentRegion))
3111 flags |= eTraversalNeeded;
3112 }
Dan Stoza23116082015-06-18 14:58:39 -07003113 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003114 if (layer->setFlags(s.flags, s.mask))
3115 flags |= eTraversalNeeded;
3116 }
3117 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003118 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003119 flags |= eTraversalNeeded;
3120 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003121 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003122 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003123 flags |= eTraversalNeeded;
3124 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003125 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003126 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003127 // We only allow setting layer stacks for top level layers,
3128 // everything else inherits layer stack from its parent.
3129 if (layer->hasParent()) {
3130 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3131 layer->getName().string());
3132 } else if (idx < 0) {
3133 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3134 "that also does not appear in the top level layer list. Something"
3135 " has gone wrong.", layer->getName().string());
3136 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003137 mCurrentState.layersSortedByZ.removeAt(idx);
3138 mCurrentState.layersSortedByZ.add(layer);
3139 // we need traversal (state changed)
3140 // AND transaction (list changed)
3141 flags |= eTransactionNeeded|eTraversalNeeded;
3142 }
3143 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003144 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003145 if (s.barrierHandle != nullptr) {
3146 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3147 } else if (s.barrierGbp != nullptr) {
3148 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3149 if (authenticateSurfaceTextureLocked(gbp)) {
3150 const auto& otherLayer =
3151 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3152 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3153 } else {
3154 ALOGE("Attempt to defer transaction to to an"
3155 " unrecognized GraphicBufferProducer");
3156 }
3157 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003158 // We don't trigger a traversal here because if no other state is
3159 // changed, we don't want this to cause any more work
3160 }
Robert Carr1db73f62016-12-21 12:58:51 -08003161 if (what & layer_state_t::eReparentChildren) {
3162 if (layer->reparentChildren(s.reparentHandle)) {
3163 flags |= eTransactionNeeded|eTraversalNeeded;
3164 }
3165 }
Robert Carr9524cb32017-02-13 11:32:32 -08003166 if (what & layer_state_t::eDetachChildren) {
3167 layer->detachChildren();
3168 }
Robert Carrc3574f72016-03-24 12:19:32 -07003169 if (what & layer_state_t::eOverrideScalingModeChanged) {
3170 layer->setOverrideScalingMode(s.overrideScalingMode);
3171 // We don't trigger a traversal here because if no other state is
3172 // changed, we don't want this to cause any more work
3173 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003174 }
3175 return flags;
3176}
3177
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003178status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003179 const String8& name,
3180 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003181 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003182 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3183 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003185 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003186 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003187 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003188 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003189 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003190
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003191 status_t result = NO_ERROR;
3192
3193 sp<Layer> layer;
3194
Cody Northropbc755282017-03-31 12:00:08 -06003195 String8 uniqueName = getUniqueLayerName(name);
3196
Mathias Agopian3165cc22012-08-08 19:42:09 -07003197 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3198 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003199 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003200 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003201 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003203 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003204 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003205 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003206 handle, gbp, &layer);
3207 break;
3208 default:
3209 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210 break;
3211 }
3212
Dan Stoza7d89d062015-04-30 13:29:25 -07003213 if (result != NO_ERROR) {
3214 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003215 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003216
Chia-I Wuab0c3192017-08-01 11:29:00 -07003217 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3218 // TODO b/64227542
3219 if (windowType == 441731) {
3220 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3221 layer->setPrimaryDisplayOnly();
3222 }
3223
Albert Chaulk479c60c2017-01-27 14:21:34 -05003224 layer->setInfo(windowType, ownerUid);
3225
Robert Carr1f0a16a2016-10-24 16:27:39 -07003226 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003227 if (result != NO_ERROR) {
3228 return result;
3229 }
Irvelffc9efc2016-07-27 15:16:37 -07003230 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003231
3232 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003233 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234}
3235
Cody Northropbc755282017-03-31 12:00:08 -06003236String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3237{
3238 bool matchFound = true;
3239 uint32_t dupeCounter = 0;
3240
3241 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3242 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3243
3244 // Loop over layers until we're sure there is no matching name
3245 while (matchFound) {
3246 matchFound = false;
3247 mDrawingState.traverseInZOrder([&](Layer* layer) {
3248 if (layer->getName() == uniqueName) {
3249 matchFound = true;
3250 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3251 }
3252 });
3253 }
3254
3255 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3256
3257 return uniqueName;
3258}
3259
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003260status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3261 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3262 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263{
3264 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003265 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003266 case PIXEL_FORMAT_TRANSPARENT:
3267 case PIXEL_FORMAT_TRANSLUCENT:
3268 format = PIXEL_FORMAT_RGBA_8888;
3269 break;
3270 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003271 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003272 break;
3273 }
3274
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003275 *outLayer = new Layer(this, client, name, w, h, flags);
3276 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3277 if (err == NO_ERROR) {
3278 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003279 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003280 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003281
3282 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3283 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003284}
3285
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003286status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3287 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3288 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003290 *outLayer = new LayerDim(this, client, name, w, h, flags);
3291 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003292 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003293 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003294}
3295
Mathias Agopianac9fa422013-02-11 16:40:36 -08003296status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003297{
Robert Carr9524cb32017-02-13 11:32:32 -08003298 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003299 status_t err = NO_ERROR;
3300 sp<Layer> l(client->getLayerUser(handle));
3301 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003302 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003303 err = removeLayer(l);
3304 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3305 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003306 }
3307 return err;
3308}
3309
Mathias Agopian13127d82013-03-05 17:47:11 -08003310status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003311{
Mathias Agopian67106042013-03-14 19:18:13 -07003312 // called by ~LayerCleaner() when all references to the IBinder (handle)
3313 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003314 sp<Layer> l = layer.promote();
3315 if (l == nullptr) {
3316 // The layer has already been removed, carry on
3317 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003318 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003319 // If we have a parent, then we can continue to live as long as it does.
3320 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003321}
3322
Mathias Agopianb60314a2012-04-10 22:09:54 -07003323// ---------------------------------------------------------------------------
3324
Andy McFadden13a082e2012-08-24 10:16:42 -07003325void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003326 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003327 Vector<ComposerState> state;
3328 Vector<DisplayState> displays;
3329 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003330 d.what = DisplayState::eDisplayProjectionChanged |
3331 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003332 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003333 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003334 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003335 d.frame.makeInvalid();
3336 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003337 d.width = 0;
3338 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003339 displays.add(d);
3340 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003341 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3342 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003343
Dan Stoza9e56aa02015-11-02 13:00:03 -08003344 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3345 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003346 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003347
Brian Andersond0010582017-03-07 13:20:31 -08003348 // Use phase of 0 since phase is not known.
3349 // Use latency of 0, which will snap to the ideal latency.
3350 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003351}
3352
3353void SurfaceFlinger::initializeDisplays() {
3354 class MessageScreenInitialized : public MessageBase {
3355 SurfaceFlinger* flinger;
3356 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003357 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003358 virtual bool handler() {
3359 flinger->onInitializeDisplays();
3360 return true;
3361 }
3362 };
3363 sp<MessageBase> msg = new MessageScreenInitialized(this);
3364 postMessageAsync(msg); // we may be called from main thread, use async message
3365}
3366
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003367void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003368 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003369 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3370 this);
3371 int32_t type = hw->getDisplayType();
3372 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003373
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003374 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003375 return;
3376 }
3377
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003378 hw->setPowerMode(mode);
3379 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3380 ALOGW("Trying to set power mode for virtual display");
3381 return;
3382 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003383
Irvelffc9efc2016-07-27 15:16:37 -07003384 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003385 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003386 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3387 if (idx < 0) {
3388 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3389 return;
3390 }
3391 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3392 }
3393
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003394 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003395 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003396 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003397 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3398 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003399 // FIXME: eventthread only knows about the main display right now
3400 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003401 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003402 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003403
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003404 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003405 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003406 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003407
3408 struct sched_param param = {0};
3409 param.sched_priority = 1;
3410 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3411 ALOGW("Couldn't set SCHED_FIFO on display on");
3412 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003413 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003414 // Turn off the display
3415 struct sched_param param = {0};
3416 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3417 ALOGW("Couldn't set SCHED_OTHER on display off");
3418 }
3419
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003420 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003421 disableHardwareVsync(true); // also cancels any in-progress resync
3422
Mathias Agopiancde87a32012-09-13 14:09:01 -07003423 // FIXME: eventthread only knows about the main display right now
3424 mEventThread->onScreenReleased();
3425 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003426
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003427 getHwComposer().setPowerMode(type, mode);
3428 mVisibleRegionsDirty = true;
3429 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003430 } else if (mode == HWC_POWER_MODE_DOZE ||
3431 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003432 // Update display while dozing
3433 getHwComposer().setPowerMode(type, mode);
3434 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3435 // FIXME: eventthread only knows about the main display right now
3436 mEventThread->onScreenAcquired();
3437 resyncToHardwareVsync(true);
3438 }
3439 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3440 // Leave display going to doze
3441 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3442 disableHardwareVsync(true); // also cancels any in-progress resync
3443 // FIXME: eventthread only knows about the main display right now
3444 mEventThread->onScreenReleased();
3445 }
3446 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003447 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003448 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003449 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003450 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003451}
3452
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003453void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3454 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003455 SurfaceFlinger& mFlinger;
3456 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003457 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003458 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003459 MessageSetPowerMode(SurfaceFlinger& flinger,
3460 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3461 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003462 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003463 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003464 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003465 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003466 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003467 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003468 ALOGW("Attempt to set power mode = %d for virtual display",
3469 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003470 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003471 mFlinger.setPowerModeInternal(
3472 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003473 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003474 return true;
3475 }
3476 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003477 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003478 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003479}
3480
3481// ---------------------------------------------------------------------------
3482
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003483status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3484{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003485 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003486
Mathias Agopianbd115332013-04-18 16:41:04 -07003487 IPCThreadState* ipc = IPCThreadState::self();
3488 const int pid = ipc->getCallingPid();
3489 const int uid = ipc->getCallingUid();
3490 if ((uid != AID_SHELL) &&
3491 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003492 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003493 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003494 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003495 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003496 // (this would indicate SF is stuck, but we want to be able to
3497 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003498 status_t err = mStateLock.timedLock(s2ns(1));
3499 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003500 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003501 result.appendFormat(
3502 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3503 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003504 }
3505
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003506 bool dumpAll = true;
3507 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003508 size_t numArgs = args.size();
3509 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003510 if ((index < numArgs) &&
3511 (args[index] == String16("--list"))) {
3512 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003513 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003514 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003515 }
3516
3517 if ((index < numArgs) &&
3518 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003519 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003520 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003521 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003522 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003523
3524 if ((index < numArgs) &&
3525 (args[index] == String16("--latency-clear"))) {
3526 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003527 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003528 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003529 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003530
3531 if ((index < numArgs) &&
3532 (args[index] == String16("--dispsync"))) {
3533 index++;
3534 mPrimaryDispSync.dump(result);
3535 dumpAll = false;
3536 }
Dan Stozab90cf072015-03-05 11:05:59 -08003537
3538 if ((index < numArgs) &&
3539 (args[index] == String16("--static-screen"))) {
3540 index++;
3541 dumpStaticScreenStats(result);
3542 dumpAll = false;
3543 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003544
3545 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003546 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003547 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003548 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003549 dumpAll = false;
3550 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003551
3552 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3553 index++;
3554 dumpWideColorInfo(result);
3555 dumpAll = false;
3556 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003557 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003558
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003559 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003560 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003561 }
3562
Mathias Agopian9795c422009-08-26 16:36:26 -07003563 if (locked) {
3564 mStateLock.unlock();
3565 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003566 }
3567 write(fd, result.string(), result.size());
3568 return NO_ERROR;
3569}
3570
Dan Stozac7014012014-02-14 15:03:43 -08003571void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3572 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003573{
Robert Carr2047fae2016-11-28 14:09:09 -08003574 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003575 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003576 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003577}
3578
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003579void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003580 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003581{
3582 String8 name;
3583 if (index < args.size()) {
3584 name = String8(args[index]);
3585 index++;
3586 }
3587
Dan Stoza9e56aa02015-11-02 13:00:03 -08003588 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3589 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003590 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003591
3592 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003593 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003594 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003595 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003596 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003597 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003598 }
Robert Carr2047fae2016-11-28 14:09:09 -08003599 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003600 }
3601}
3602
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003603void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003604 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003605{
3606 String8 name;
3607 if (index < args.size()) {
3608 name = String8(args[index]);
3609 index++;
3610 }
3611
Robert Carr2047fae2016-11-28 14:09:09 -08003612 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003613 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003614 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003615 }
Robert Carr2047fae2016-11-28 14:09:09 -08003616 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003617
Svetoslavd85084b2014-03-20 10:28:31 -07003618 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003619}
3620
Jamie Gennis6547ff42013-07-16 20:12:42 -07003621// This should only be called from the main thread. Otherwise it would need
3622// the lock and should use mCurrentState rather than mDrawingState.
3623void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003624 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003625 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003626 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003627
3628 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3629}
3630
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003631void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003632{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003633 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003634 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3635
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003636 if (isLayerTripleBufferingDisabled())
3637 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003638
3639 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003640 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003641 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003642 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003643 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3644 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003645 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003646}
3647
Dan Stozab90cf072015-03-05 11:05:59 -08003648void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3649{
3650 result.appendFormat("Static screen stats:\n");
3651 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3652 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3653 float percent = 100.0f *
3654 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3655 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3656 b + 1, bucketTimeSec, percent);
3657 }
3658 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3659 float percent = 100.0f *
3660 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3661 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3662 NUM_BUCKETS - 1, bucketTimeSec, percent);
3663}
3664
Dan Stozae77c7662016-05-13 11:37:28 -07003665void SurfaceFlinger::recordBufferingStats(const char* layerName,
3666 std::vector<OccupancyTracker::Segment>&& history) {
3667 Mutex::Autolock lock(mBufferingStatsMutex);
3668 auto& stats = mBufferingStats[layerName];
3669 for (const auto& segment : history) {
3670 if (!segment.usedThirdBuffer) {
3671 stats.twoBufferTime += segment.totalTime;
3672 }
3673 if (segment.occupancyAverage < 1.0f) {
3674 stats.doubleBufferedTime += segment.totalTime;
3675 } else if (segment.occupancyAverage < 2.0f) {
3676 stats.tripleBufferedTime += segment.totalTime;
3677 }
3678 ++stats.numSegments;
3679 stats.totalTime += segment.totalTime;
3680 }
3681}
3682
Brian Andersond6927fb2016-07-23 23:37:30 -07003683void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3684 result.appendFormat("Layer frame timestamps:\n");
3685
3686 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3687 const size_t count = currentLayers.size();
3688 for (size_t i=0 ; i<count ; i++) {
3689 currentLayers[i]->dumpFrameEvents(result);
3690 }
3691}
3692
Dan Stozae77c7662016-05-13 11:37:28 -07003693void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3694 result.append("Buffering stats:\n");
3695 result.append(" [Layer name] <Active time> <Two buffer> "
3696 "<Double buffered> <Triple buffered>\n");
3697 Mutex::Autolock lock(mBufferingStatsMutex);
3698 typedef std::tuple<std::string, float, float, float> BufferTuple;
3699 std::map<float, BufferTuple, std::greater<float>> sorted;
3700 for (const auto& statsPair : mBufferingStats) {
3701 const char* name = statsPair.first.c_str();
3702 const BufferingStats& stats = statsPair.second;
3703 if (stats.numSegments == 0) {
3704 continue;
3705 }
3706 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3707 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3708 stats.totalTime;
3709 float doubleBufferRatio = static_cast<float>(
3710 stats.doubleBufferedTime) / stats.totalTime;
3711 float tripleBufferRatio = static_cast<float>(
3712 stats.tripleBufferedTime) / stats.totalTime;
3713 sorted.insert({activeTime, {name, twoBufferRatio,
3714 doubleBufferRatio, tripleBufferRatio}});
3715 }
3716 for (const auto& sortedPair : sorted) {
3717 float activeTime = sortedPair.first;
3718 const BufferTuple& values = sortedPair.second;
3719 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3720 std::get<0>(values).c_str(), activeTime,
3721 std::get<1>(values), std::get<2>(values),
3722 std::get<3>(values));
3723 }
3724 result.append("\n");
3725}
3726
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003727void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3728 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3729
3730 // TODO: print out if wide-color mode is active or not
3731
3732 for (size_t d = 0; d < mDisplays.size(); d++) {
3733 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3734 int32_t hwcId = displayDevice->getHwcDisplayId();
3735 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3736 continue;
3737 }
3738
3739 result.appendFormat("Display %d color modes:\n", hwcId);
3740 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3741 for (auto&& mode : modes) {
3742 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3743 }
3744
3745 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3746 result.appendFormat(" Current color mode: %s (%d)\n",
3747 decodeColorMode(currentMode).c_str(), currentMode);
3748 }
3749 result.append("\n");
3750}
3751
Mathias Agopian74d211a2013-04-22 16:55:35 +02003752void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3753 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003754{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003755 bool colorize = false;
3756 if (index < args.size()
3757 && (args[index] == String16("--color"))) {
3758 colorize = true;
3759 index++;
3760 }
3761
3762 Colorizer colorizer(colorize);
3763
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003764 // figure out if we're stuck somewhere
3765 const nsecs_t now = systemTime();
3766 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3767 const nsecs_t inTransaction(mDebugInTransaction);
3768 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3769 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3770
3771 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003772 * Dump library configuration.
3773 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003774
3775 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003776 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003777 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003778 appendSfConfigString(result);
3779 appendUiConfigString(result);
3780 appendGuiConfigString(result);
3781 result.append("\n");
3782
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003783 result.append("\nWide-Color information:\n");
3784 dumpWideColorInfo(result);
3785
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003786 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003787 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003788 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003789 result.append(SyncFeatures::getInstance().toString());
3790 result.append("\n");
3791
Dan Stoza9e56aa02015-11-02 13:00:03 -08003792 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3793
Andy McFadden41d67d72014-04-25 16:58:34 -07003794 colorizer.bold(result);
3795 result.append("DispSync configuration: ");
3796 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003797 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003798 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003799 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003800 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003801 result.append("\n");
3802
Dan Stozab90cf072015-03-05 11:05:59 -08003803 // Dump static screen stats
3804 result.append("\n");
3805 dumpStaticScreenStats(result);
3806 result.append("\n");
3807
Dan Stozae77c7662016-05-13 11:37:28 -07003808 dumpBufferingStats(result);
3809
Andy McFadden4803b742012-09-24 19:07:20 -07003810 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003811 * Dump the visible layer list
3812 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003813 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003814 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003815 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003816 mCurrentState.traverseInZOrder([&](Layer* layer) {
Kalle Raitaa099a242017-01-11 11:17:29 -08003817 result.append(to_string(layer->getLayerDebugInfo()).c_str());
Robert Carr2047fae2016-11-28 14:09:09 -08003818 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003819
3820 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003821 * Dump Display state
3822 */
3823
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003824 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003825 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003826 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003827 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3828 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003829 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003830 }
3831
3832 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003833 * Dump SurfaceFlinger global state
3834 */
3835
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003836 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003837 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003838 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003839
Mathias Agopian888c8222012-08-04 21:10:38 -07003840 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003841 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003842
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003843 colorizer.bold(result);
3844 result.appendFormat("EGL implementation : %s\n",
3845 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3846 colorizer.reset(result);
3847 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003848 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003849
Mathias Agopian875d8e12013-06-07 15:35:48 -07003850 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003851
Mathias Agopian42977342012-08-05 00:40:46 -07003852 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003853 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3854 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003855 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003856 " last eglSwapBuffers() time: %f us\n"
3857 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003858 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003859 " refresh-rate : %f fps\n"
3860 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003861 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003862 " gpu_to_cpu_unsupported : %d\n"
3863 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003864 mLastSwapBufferTime/1000.0,
3865 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003866 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003867 1e9 / activeConfig->getVsyncPeriod(),
3868 activeConfig->getDpiX(),
3869 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003870 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003871
Mathias Agopian74d211a2013-04-22 16:55:35 +02003872 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003873 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003874
Mathias Agopian74d211a2013-04-22 16:55:35 +02003875 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003876 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003877
3878 /*
3879 * VSYNC state
3880 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003881 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003882 result.append("\n");
3883
3884 /*
3885 * HWC layer minidump
3886 */
3887 for (size_t d = 0; d < mDisplays.size(); d++) {
3888 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3889 int32_t hwcId = displayDevice->getHwcDisplayId();
3890 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3891 continue;
3892 }
3893
3894 result.appendFormat("Display %d HWC layers:\n", hwcId);
3895 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003896 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003897 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003898 });
Dan Stozae22aec72016-08-01 13:20:59 -07003899 result.append("\n");
3900 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003901
3902 /*
3903 * Dump HWComposer state
3904 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003905 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003906 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003907 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003908 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003909 result.appendFormat(" h/w composer %s\n",
3910 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003911 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003912
3913 /*
3914 * Dump gralloc state
3915 */
3916 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3917 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003918
3919 /*
3920 * Dump VrFlinger state if in use.
3921 */
3922 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3923 result.append("VrFlinger state:\n");
3924 result.append(mVrFlinger->Dump().c_str());
3925 result.append("\n");
3926 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003927}
3928
Mathias Agopian13127d82013-03-05 17:47:11 -08003929const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003930SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003931 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003932 wp<IBinder> dpy;
3933 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3934 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3935 dpy = mDisplays.keyAt(i);
3936 break;
3937 }
3938 }
3939 if (dpy == NULL) {
3940 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3941 // Just use the primary display so we have something to return
3942 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3943 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003944 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003945}
3946
Keun young Park63f165f2012-08-31 10:53:36 -07003947bool SurfaceFlinger::startDdmConnection()
3948{
3949 void* libddmconnection_dso =
3950 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3951 if (!libddmconnection_dso) {
3952 return false;
3953 }
3954 void (*DdmConnection_start)(const char* name);
3955 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003956 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003957 if (!DdmConnection_start) {
3958 dlclose(libddmconnection_dso);
3959 return false;
3960 }
3961 (*DdmConnection_start)(getServiceName());
3962 return true;
3963}
3964
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003965status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003966 switch (code) {
3967 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003968 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003969 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003970 case CLEAR_ANIMATION_FRAME_STATS:
3971 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003972 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003973 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003974 {
3975 // codes that require permission check
3976 IPCThreadState* ipc = IPCThreadState::self();
3977 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003978 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003979 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003980 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003981 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003982 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003983 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003984 break;
3985 }
Robert Carr1db73f62016-12-21 12:58:51 -08003986 /*
3987 * Calling setTransactionState is safe, because you need to have been
3988 * granted a reference to Client* and Handle* to do anything with it.
3989 *
3990 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3991 */
3992 case SET_TRANSACTION_STATE:
3993 case CREATE_SCOPED_CONNECTION:
3994 {
3995 return OK;
3996 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003997 case CAPTURE_SCREEN:
3998 {
3999 // codes that require permission check
4000 IPCThreadState* ipc = IPCThreadState::self();
4001 const int pid = ipc->getCallingPid();
4002 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004003 if ((uid != AID_GRAPHICS) &&
4004 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004005 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004006 return PERMISSION_DENIED;
4007 }
4008 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004009 }
4010 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004011 return OK;
4012}
4013
4014status_t SurfaceFlinger::onTransact(
4015 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4016{
4017 status_t credentialCheck = CheckTransactCodeCredentials(code);
4018 if (credentialCheck != OK) {
4019 return credentialCheck;
4020 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004021
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004022 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4023 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004024 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004025 IPCThreadState* ipc = IPCThreadState::self();
4026 const int uid = ipc->getCallingUid();
4027 if (CC_UNLIKELY(uid != AID_SYSTEM
4028 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004029 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004030 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004031 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004032 return PERMISSION_DENIED;
4033 }
4034 int n;
4035 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004036 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004037 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004038 return NO_ERROR;
4039 case 1002: // SHOW_UPDATES
4040 n = data.readInt32();
4041 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004042 invalidateHwcGeometry();
4043 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004044 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004045 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004046 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004047 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004048 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004049 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004050 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004051 setTransactionFlags(
4052 eTransactionNeeded|
4053 eDisplayTransactionNeeded|
4054 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004055 return NO_ERROR;
4056 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004057 case 1006:{ // send empty update
4058 signalRefresh();
4059 return NO_ERROR;
4060 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004061 case 1008: // toggle use of hw composer
4062 n = data.readInt32();
4063 mDebugDisableHWC = n ? 1 : 0;
4064 invalidateHwcGeometry();
4065 repaintEverything();
4066 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004067 case 1009: // toggle use of transform hint
4068 n = data.readInt32();
4069 mDebugDisableTransformHint = n ? 1 : 0;
4070 invalidateHwcGeometry();
4071 repaintEverything();
4072 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004073 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004074 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004075 reply->writeInt32(0);
4076 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004077 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004078 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004079 return NO_ERROR;
4080 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004081 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004082 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004083 return NO_ERROR;
4084 }
4085 case 1014: {
4086 // daltonize
4087 n = data.readInt32();
4088 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004089 case 1:
4090 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4091 break;
4092 case 2:
4093 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4094 break;
4095 case 3:
4096 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4097 break;
4098 default:
4099 mDaltonizer.setType(ColorBlindnessType::None);
4100 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004101 }
4102 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004103 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004104 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004105 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004106 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004107 invalidateHwcGeometry();
4108 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004109 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004110 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004111 case 1015: {
4112 // apply a color matrix
4113 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004114 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004115 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004116 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004117 for (size_t j = 0; j < 4; j++) {
4118 mColorMatrix[i][j] = data.readFloat();
4119 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004120 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004121 } else {
4122 mColorMatrix = mat4();
4123 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004124
4125 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4126 // the division by w in the fragment shader
4127 float4 lastRow(transpose(mColorMatrix)[3]);
4128 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4129 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4130 }
4131
Alan Viverette9c5a3332013-09-12 20:04:35 -07004132 invalidateHwcGeometry();
4133 repaintEverything();
4134 return NO_ERROR;
4135 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004136 // This is an experimental interface
4137 // Needs to be shifted to proper binder interface when we productize
4138 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004139 n = data.readInt32();
4140 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004141 return NO_ERROR;
4142 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004143 case 1017: {
4144 n = data.readInt32();
4145 mForceFullDamage = static_cast<bool>(n);
4146 return NO_ERROR;
4147 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004148 case 1018: { // Modify Choreographer's phase offset
4149 n = data.readInt32();
4150 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4151 return NO_ERROR;
4152 }
4153 case 1019: { // Modify SurfaceFlinger's phase offset
4154 n = data.readInt32();
4155 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4156 return NO_ERROR;
4157 }
Irvel468051e2016-06-13 16:44:44 -07004158 case 1020: { // Layer updates interceptor
4159 n = data.readInt32();
4160 if (n) {
4161 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004162 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004163 }
4164 else{
4165 ALOGV("Interceptor disabled");
4166 mInterceptor.disable();
4167 }
4168 return NO_ERROR;
4169 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004170 case 1021: { // Disable HWC virtual displays
4171 n = data.readInt32();
4172 mUseHwcVirtualDisplays = !n;
4173 return NO_ERROR;
4174 }
Romain Guy0147a172017-06-01 13:53:56 -07004175 case 1022: { // Set saturation boost
4176 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4177
4178 invalidateHwcGeometry();
4179 repaintEverything();
4180 return NO_ERROR;
4181 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004182 }
4183 }
4184 return err;
4185}
4186
Steven Thomas6d8110b2017-08-31 18:24:21 -07004187void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004188 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004189 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004190}
4191
Steven Thomas6d8110b2017-08-31 18:24:21 -07004192void SurfaceFlinger::repaintEverything() {
4193 ConditionalLock _l(mStateLock,
4194 std::this_thread::get_id() != mMainThreadId);
4195 repaintEverythingLocked();
4196}
4197
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004198// Checks that the requested width and height are valid and updates them to the display dimensions
4199// if they are set to 0
4200static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4201 Transform::orientation_flags rotation,
4202 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4203 // get screen geometry
4204 uint32_t displayWidth = displayDevice->getWidth();
4205 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004206
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004207 if (rotation & Transform::ROT_90) {
4208 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004209 }
4210
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004211 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4212 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4213 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4214 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004215 }
4216
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004217 if (*requestedWidth == 0) {
4218 *requestedWidth = displayWidth;
4219 }
4220 if (*requestedHeight == 0) {
4221 *requestedHeight = displayHeight;
4222 }
4223
4224 return NO_ERROR;
4225}
4226
4227// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4228class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004229public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004230 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4231 ~WindowDisconnector() {
4232 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004233 }
4234
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004235private:
4236 ANativeWindow* mWindow;
4237 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004238};
4239
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004240static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4241 uint32_t requestedHeight, bool hasWideColorDisplay,
4242 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4243 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4244 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4245
4246 int err = 0;
4247 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4248 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4249 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4250 err |= native_window_set_usage(window, usage);
4251
4252 if (hasWideColorDisplay) {
4253 err |= native_window_set_buffers_data_space(window,
4254 renderEngineUsesWideColor
4255 ? HAL_DATASPACE_DISPLAY_P3
4256 : HAL_DATASPACE_V0_SRGB);
4257 }
4258
4259 if (err != NO_ERROR) {
4260 return BAD_VALUE;
4261 }
4262
4263 /* TODO: Once we have the sync framework everywhere this can use
4264 * server-side waits on the fence that dequeueBuffer returns.
4265 */
4266 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4267 if (err != NO_ERROR) {
4268 return err;
4269 }
4270
4271 return NO_ERROR;
4272}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004273
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004274status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4275 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004276 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004277 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004278 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004279 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004280
4281 if (CC_UNLIKELY(display == 0))
4282 return BAD_VALUE;
4283
4284 if (CC_UNLIKELY(producer == 0))
4285 return BAD_VALUE;
4286
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004287 // if we have secure windows on this display, never allow the screen capture
4288 // unless the producer interface is local (i.e.: we can take a screenshot for
4289 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004290 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004291
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004292 // Convert to surfaceflinger's internal rotation type.
4293 Transform::orientation_flags rotationFlags;
4294 switch (rotation) {
4295 case ISurfaceComposer::eRotateNone:
4296 rotationFlags = Transform::ROT_0;
4297 break;
4298 case ISurfaceComposer::eRotate90:
4299 rotationFlags = Transform::ROT_90;
4300 break;
4301 case ISurfaceComposer::eRotate180:
4302 rotationFlags = Transform::ROT_180;
4303 break;
4304 case ISurfaceComposer::eRotate270:
4305 rotationFlags = Transform::ROT_270;
4306 break;
4307 default:
4308 rotationFlags = Transform::ROT_0;
4309 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4310 break;
4311 }
4312
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004313 { // Autolock scope
4314 Mutex::Autolock lock(mStateLock);
4315 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4316 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004317 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004318
4319 // create a surface (because we're a producer, and we need to
4320 // dequeue/queue a buffer)
4321 sp<Surface> surface = new Surface(producer, false);
4322
4323 // Put the screenshot Surface into async mode so that
4324 // Layer::headFenceHasSignaled will always return true and we'll latch the
4325 // first buffer regardless of whether or not its acquire fence has
4326 // signaled. This is needed to avoid a race condition in the rotation
4327 // animation. See b/30209608
4328 surface->setAsyncMode(true);
4329
4330 ANativeWindow* window = surface.get();
4331
4332 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4333 if (result != NO_ERROR) {
4334 return result;
4335 }
4336 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4337
4338 ANativeWindowBuffer* buffer = nullptr;
4339 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4340 getRenderEngine().usesWideColor(), &buffer);
4341 if (result != NO_ERROR) {
4342 return result;
4343 }
4344
4345 // This mutex protects syncFd and captureResult for communication of the return values from the
4346 // main thread back to this Binder thread
4347 std::mutex captureMutex;
4348 std::condition_variable captureCondition;
4349 std::unique_lock<std::mutex> captureLock(captureMutex);
4350 int syncFd = -1;
4351 std::optional<status_t> captureResult;
4352
4353 sp<LambdaMessage> message = new LambdaMessage([&]() {
4354 // If there is a refresh pending, bug out early and tell the binder thread to try again
4355 // after the refresh.
4356 if (mRefreshPending) {
4357 ATRACE_NAME("Skipping screenshot for now");
4358 std::unique_lock<std::mutex> captureLock(captureMutex);
4359 captureResult = std::make_optional<status_t>(EAGAIN);
4360 captureCondition.notify_one();
4361 return;
4362 }
4363
4364 status_t result = NO_ERROR;
4365 int fd = -1;
4366 {
4367 Mutex::Autolock _l(mStateLock);
4368 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4369 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4370 minLayerZ, maxLayerZ, useIdentityTransform,
4371 rotationFlags, isLocalScreenshot, &fd);
4372 }
4373
4374 {
4375 std::unique_lock<std::mutex> captureLock(captureMutex);
4376 syncFd = fd;
4377 captureResult = std::make_optional<status_t>(result);
4378 captureCondition.notify_one();
4379 }
4380 });
4381
4382 result = postMessageAsync(message);
4383 if (result == NO_ERROR) {
4384 captureCondition.wait(captureLock, [&]() { return captureResult; });
4385 while (*captureResult == EAGAIN) {
4386 captureResult.reset();
4387 result = postMessageAsync(message);
4388 if (result != NO_ERROR) {
4389 return result;
4390 }
4391 captureCondition.wait(captureLock, [&]() { return captureResult; });
4392 }
4393 result = *captureResult;
4394 }
4395
4396 if (result == NO_ERROR) {
4397 // queueBuffer takes ownership of syncFd
4398 result = window->queueBuffer(window, buffer, syncFd);
4399 }
4400
4401 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004402}
4403
Mathias Agopian180f10d2013-04-10 22:55:41 -07004404
4405void SurfaceFlinger::renderScreenImplLocked(
4406 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004407 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004408 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004409 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004410{
4411 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004412 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004413
4414 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004415 const int32_t hw_w = hw->getWidth();
4416 const int32_t hw_h = hw->getHeight();
4417 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004418 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004419
Dan Stozac1879002014-05-22 15:59:05 -07004420 // if a default or invalid sourceCrop is passed in, set reasonable values
4421 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4422 !sourceCrop.isValid()) {
4423 sourceCrop.setLeftTop(Point(0, 0));
4424 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4425 }
4426
4427 // ensure that sourceCrop is inside screen
4428 if (sourceCrop.left < 0) {
4429 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4430 }
Dan Stozabe31f442014-06-11 11:20:54 -07004431 if (sourceCrop.right > hw_w) {
4432 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004433 }
4434 if (sourceCrop.top < 0) {
4435 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4436 }
Dan Stozabe31f442014-06-11 11:20:54 -07004437 if (sourceCrop.bottom > hw_h) {
4438 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004439 }
4440
Romain Guy88d37dd2017-05-26 17:57:05 -07004441#ifdef USE_HWC2
4442 engine.setWideColor(hw->getWideColorSupport());
4443 engine.setColorMode(hw->getActiveColorMode());
4444#endif
4445
Mathias Agopian180f10d2013-04-10 22:55:41 -07004446 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004447 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004448
4449 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004450 engine.setViewportAndProjection(
4451 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004452 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004453
4454 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004455 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004456
Robert Carr1f0a16a2016-10-24 16:27:39 -07004457 // We loop through the first level of layers without traversing,
4458 // as we need to interpret min/max layer Z in the top level Z space.
4459 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004460 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004461 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004462 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004463 const Layer::State& state(layer->getDrawingState());
4464 if (state.z < minLayerZ || state.z > maxLayerZ) {
4465 continue;
4466 }
Dan Stoza412903f2017-04-27 13:42:17 -07004467 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004468 if (!layer->isVisible()) {
4469 return;
4470 }
4471 if (filtering) layer->setFiltering(true);
4472 layer->draw(hw, useIdentityTransform);
4473 if (filtering) layer->setFiltering(false);
4474 });
4475 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004476
Mathias Agopian931bda12013-08-28 18:11:46 -07004477 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004478}
4479
Dan Stozaabcda352017-06-01 14:37:39 -07004480// A simple RAII class that holds an EGLImage and destroys it either:
4481// a) When the destroy() method is called
4482// b) When the object goes out of scope
4483class ImageHolder {
4484public:
4485 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4486 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004487
Dan Stozaabcda352017-06-01 14:37:39 -07004488 void destroy() {
4489 if (mImage != EGL_NO_IMAGE_KHR) {
4490 eglDestroyImageKHR(mDisplay, mImage);
4491 mImage = EGL_NO_IMAGE_KHR;
4492 }
4493 }
4494
4495private:
4496 const EGLDisplay mDisplay;
4497 EGLImageKHR mImage;
4498};
4499
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004500status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4501 ANativeWindowBuffer* buffer, Rect sourceCrop,
4502 uint32_t reqWidth, uint32_t reqHeight,
4503 int32_t minLayerZ, int32_t maxLayerZ,
4504 bool useIdentityTransform,
4505 Transform::orientation_flags rotation,
4506 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004507 ATRACE_CALL();
4508
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004509 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004510 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004511 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004512 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004513 (state.z < minLayerZ || state.z > maxLayerZ)) {
4514 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004515 }
Dan Stoza412903f2017-04-27 13:42:17 -07004516 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004517 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4518 layer->isSecure());
4519 });
4520 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004521
4522 if (!isLocalScreenshot && secureLayerIsVisible) {
4523 ALOGW("FB is protected: PERMISSION_DENIED");
4524 return PERMISSION_DENIED;
4525 }
4526
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004527 int syncFd = -1;
4528 // create an EGLImage from the buffer so we can later
4529 // turn it into a texture
4530 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4531 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4532 if (image == EGL_NO_IMAGE_KHR) {
4533 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004534 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004535
Dan Stozaabcda352017-06-01 14:37:39 -07004536 // This will automatically destroy the image if we return before calling its destroy method
4537 ImageHolder imageHolder(mEGLDisplay, image);
4538
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004539 // this binds the given EGLImage as a framebuffer for the
4540 // duration of this scope.
4541 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004542 if (imageBond.getStatus() != NO_ERROR) {
4543 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004544 return INVALID_OPERATION;
4545 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004546
Dan Stozaabcda352017-06-01 14:37:39 -07004547 // this will in fact render into our dequeued buffer
4548 // via an FBO, which means we didn't have to create
4549 // an EGLSurface and therefore we're not
4550 // dependent on the context's EGLConfig.
4551 renderScreenImplLocked(
4552 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4553 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004554
Dan Stozaabcda352017-06-01 14:37:39 -07004555 // Attempt to create a sync khr object that can produce a sync point. If that
4556 // isn't available, create a non-dupable sync object in the fallback path and
4557 // wait on it directly.
4558 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4559 if (!DEBUG_SCREENSHOTS) {
4560 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4561 // native fence fd will not be populated until flush() is done.
4562 getRenderEngine().flush();
4563 }
4564
4565 if (sync != EGL_NO_SYNC_KHR) {
4566 // get the sync fd
4567 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4568 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4569 ALOGW("captureScreen: failed to dup sync khr object");
4570 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004571 }
Dan Stozaabcda352017-06-01 14:37:39 -07004572 eglDestroySyncKHR(mEGLDisplay, sync);
4573 } else {
4574 // fallback path
4575 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004576 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004577 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4578 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4579 EGLint eglErr = eglGetError();
4580 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4581 ALOGW("captureScreen: fence wait timed out");
4582 } else {
4583 ALOGW_IF(eglErr != EGL_SUCCESS,
4584 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004585 }
4586 eglDestroySyncKHR(mEGLDisplay, sync);
4587 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004588 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004589 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004590 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004591 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004592
4593 if (DEBUG_SCREENSHOTS) {
4594 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4595 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4596 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4597 hw, minLayerZ, maxLayerZ);
4598 delete [] pixels;
4599 }
4600
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004601 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004602 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004603
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004604 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004605}
4606
Mathias Agopiand5556842013-09-19 17:08:37 -07004607void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004608 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004609 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004610 for (size_t y=0 ; y<h ; y++) {
4611 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4612 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004613 if (p[x] != 0xFF000000) return;
4614 }
4615 }
4616 ALOGE("*** we just took a black screenshot ***\n"
4617 "requested minz=%d, maxz=%d, layerStack=%d",
4618 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004619
Robert Carr2047fae2016-11-28 14:09:09 -08004620 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004621 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004622 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004623 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004624 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004625 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004626 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4627 layer->isVisible() ? '+' : '-',
4628 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004629 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004630 i++;
4631 });
4632 }
4633 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004634 }
4635}
4636
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004637// ---------------------------------------------------------------------------
4638
Dan Stoza412903f2017-04-27 13:42:17 -07004639void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4640 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004641}
4642
Dan Stoza412903f2017-04-27 13:42:17 -07004643void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4644 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004645}
4646
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004647}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004648
4649
4650#if defined(__gl_h_)
4651#error "don't include gl/gl.h in this file"
4652#endif
4653
4654#if defined(__gl2_h_)
4655#error "don't include gl2/gl2.h in this file"
4656#endif