blob: 0b5262de30372060e7ad5f16e74841b391aafcd1 [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)
2134 for (size_t i=0 ; i<dc ; i++) {
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);
2169 dc--; i--;
2170 // 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 }
2191 }
2192
2193 // find displays that were added
2194 // (ie: in current state but not in drawing state)
2195 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002196 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002197 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002198
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002199 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002200 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002201 sp<IGraphicBufferProducer> bqProducer;
2202 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002203 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002204
Dan Stoza9e56aa02015-11-02 13:00:03 -08002205 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002206 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002207 // Virtual displays without a surface are dormant:
2208 // they have external state (layer stack, projection,
2209 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002210 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002211
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002212 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002213 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002214 int width = 0;
2215 int status = state.surface->query(
2216 NATIVE_WINDOW_WIDTH, &width);
2217 ALOGE_IF(status != NO_ERROR,
2218 "Unable to query width (%d)", status);
2219 int height = 0;
2220 status = state.surface->query(
2221 NATIVE_WINDOW_HEIGHT, &height);
2222 ALOGE_IF(status != NO_ERROR,
2223 "Unable to query height (%d)", status);
2224 int intFormat = 0;
2225 status = state.surface->query(
2226 NATIVE_WINDOW_FORMAT, &intFormat);
2227 ALOGE_IF(status != NO_ERROR,
2228 "Unable to query format (%d)", status);
2229 auto format = static_cast<android_pixel_format_t>(
2230 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002231
Dan Stoza8cf150a2016-08-02 10:27:31 -07002232 mHwc->allocateVirtualDisplay(width, height, &format,
2233 &hwcId);
2234 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002235
Dan Stoza5cf424b2016-05-20 14:02:39 -07002236 // TODO: Plumb requested format back up to consumer
2237
Dan Stoza9e56aa02015-11-02 13:00:03 -08002238 sp<VirtualDisplaySurface> vds =
2239 new VirtualDisplaySurface(*mHwc,
2240 hwcId, state.surface, bqProducer,
2241 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002242
2243 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002244 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002245 }
2246 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002247 ALOGE_IF(state.surface!=NULL,
2248 "adding a supported display, but rendering "
2249 "surface is provided (%p), ignoring it",
2250 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002251
2252 hwcId = state.type;
2253 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2254 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002255 }
2256
2257 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002258 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002259 sp<DisplayDevice> hw =
2260 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2261 dispSurface, producer,
2262 mRenderEngine->getEGLConfig(),
2263 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002264 hw->setLayerStack(state.layerStack);
2265 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002266 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002267 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002268 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002269 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002270 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002271 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002272 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002273 }
2274 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002275 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002276 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002277
Mathias Agopian84300952012-11-21 16:02:13 -08002278 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2279 // The transform hint might have changed for some layers
2280 // (either because a display has changed, or because a layer
2281 // as changed).
2282 //
2283 // Walk through all the layers in currentLayers,
2284 // and update their transform hint.
2285 //
2286 // If a layer is visible only on a single display, then that
2287 // display is used to calculate the hint, otherwise we use the
2288 // default display.
2289 //
2290 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2291 // the hint is set before we acquire a buffer from the surface texture.
2292 //
2293 // NOTE: layer transactions have taken place already, so we use their
2294 // drawing state. However, SurfaceFlinger's own transaction has not
2295 // happened yet, so we must use the current state layer list
2296 // (soon to become the drawing state list).
2297 //
2298 sp<const DisplayDevice> disp;
2299 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002300 bool first = true;
2301 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002302 // NOTE: we rely on the fact that layers are sorted by
2303 // layerStack first (so we don't have to traverse the list
2304 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002305 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002306 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002307 currentlayerStack = layerStack;
2308 // figure out if this layerstack is mirrored
2309 // (more than one display) if so, pick the default display,
2310 // if not, pick the only display it's on.
2311 disp.clear();
2312 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2313 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002314 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002315 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002316 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002317 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002318 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002319 break;
2320 }
2321 }
2322 }
2323 }
Chet Haase91d25932013-04-11 15:24:55 -07002324 if (disp == NULL) {
2325 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2326 // redraw after transform hint changes. See bug 8508397.
2327
2328 // could be null when this layer is using a layerStack
2329 // that is not visible on any display. Also can occur at
2330 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002331 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002332 }
Chet Haase91d25932013-04-11 15:24:55 -07002333 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002334
2335 first = false;
2336 });
Mathias Agopian84300952012-11-21 16:02:13 -08002337 }
2338
2339
Mathias Agopian3559b072012-08-15 13:46:03 -07002340 /*
2341 * Perform our own transaction if needed
2342 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002343
2344 if (mLayersAdded) {
2345 mLayersAdded = false;
2346 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002347 mVisibleRegionsDirty = true;
2348 }
2349
2350 // some layers might have been removed, so
2351 // we need to update the regions they're exposing.
2352 if (mLayersRemoved) {
2353 mLayersRemoved = false;
2354 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002355 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002356 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002357 // this layer is not visible anymore
2358 // TODO: we could traverse the tree from front to back and
2359 // compute the actual visible region
2360 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002361 Region visibleReg;
2362 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002363 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002364 }
Robert Carr2047fae2016-11-28 14:09:09 -08002365 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002366 }
2367
2368 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002369
2370 updateCursorAsync();
2371}
2372
2373void SurfaceFlinger::updateCursorAsync()
2374{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002375 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2376 auto& displayDevice = mDisplays[displayId];
2377 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002378 continue;
2379 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002380
2381 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2382 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002383 }
2384 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002385}
2386
2387void SurfaceFlinger::commitTransaction()
2388{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002389 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002390 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002391 for (const auto& l : mLayersPendingRemoval) {
2392 recordBufferingStats(l->getName().string(),
2393 l->getOccupancyHistory(true));
2394 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002395 }
2396 mLayersPendingRemoval.clear();
2397 }
2398
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002399 // If this transaction is part of a window animation then the next frame
2400 // we composite should be considered an animation as well.
2401 mAnimCompositionPending = mAnimTransactionPending;
2402
Mathias Agopian4fec8732012-06-29 14:12:52 -07002403 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002404 mDrawingState.traverseInZOrder([](Layer* layer) {
2405 layer->commitChildList();
2406 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002407 mTransactionPending = false;
2408 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002409 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002410}
2411
Chia-I Wuab0c3192017-08-01 11:29:00 -07002412void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002413 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002414{
Mathias Agopian841cde52012-03-01 15:44:37 -08002415 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002416 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002417
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002418 Region aboveOpaqueLayers;
2419 Region aboveCoveredLayers;
2420 Region dirty;
2421
Mathias Agopian87baae12012-07-31 12:38:26 -07002422 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002423
Robert Carr2047fae2016-11-28 14:09:09 -08002424 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002425 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002426 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002427
Jesse Hall01e29052013-02-19 16:13:35 -08002428 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002429 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002430 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002431
Mathias Agopianab028732010-03-16 16:41:46 -07002432 /*
2433 * opaqueRegion: area of a surface that is fully opaque.
2434 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002435 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002436
2437 /*
2438 * visibleRegion: area of a surface that is visible on screen
2439 * and not fully transparent. This is essentially the layer's
2440 * footprint minus the opaque regions above it.
2441 * Areas covered by a translucent surface are considered visible.
2442 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002443 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002444
2445 /*
2446 * coveredRegion: area of a surface that is covered by all
2447 * visible regions above it (which includes the translucent areas).
2448 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002450
Jesse Halla8026d22012-09-25 13:25:04 -07002451 /*
2452 * transparentRegion: area of a surface that is hinted to be completely
2453 * transparent. This is only used to tell when the layer has no visible
2454 * non-transparent regions and can be removed from the layer list. It
2455 * does not affect the visibleRegion of this layer or any layers
2456 * beneath it. The hint may not be correct if apps don't respect the
2457 * SurfaceView restrictions (which, sadly, some don't).
2458 */
2459 Region transparentRegion;
2460
Mathias Agopianab028732010-03-16 16:41:46 -07002461
2462 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002463 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002464 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002465 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002466 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002467 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002468 if (!visibleRegion.isEmpty()) {
2469 // Remove the transparent area from the visible region
2470 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002471 if (tr.preserveRects()) {
2472 // transform the transparent region
2473 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002474 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002475 // transformation too complex, can't do the
2476 // transparent region optimization.
2477 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002478 }
Mathias Agopianab028732010-03-16 16:41:46 -07002479 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480
Mathias Agopianab028732010-03-16 16:41:46 -07002481 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002482 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002484 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2485 // the opaque region is the layer's footprint
2486 opaqueRegion = visibleRegion;
2487 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002488 }
2489 }
2490
Mathias Agopianab028732010-03-16 16:41:46 -07002491 // Clip the covered region to the visible region
2492 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2493
2494 // Update aboveCoveredLayers for next (lower) layer
2495 aboveCoveredLayers.orSelf(visibleRegion);
2496
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497 // subtract the opaque region covered by the layers above us
2498 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499
2500 // compute this layer's dirty region
2501 if (layer->contentDirty) {
2502 // we need to invalidate the whole region
2503 dirty = visibleRegion;
2504 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002505 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506 layer->contentDirty = false;
2507 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002508 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002509 * the exposed region consists of two components:
2510 * 1) what's VISIBLE now and was COVERED before
2511 * 2) what's EXPOSED now less what was EXPOSED before
2512 *
2513 * note that (1) is conservative, we start with the whole
2514 * visible region but only keep what used to be covered by
2515 * something -- which mean it may have been exposed.
2516 *
2517 * (2) handles areas that were not covered by anything but got
2518 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002519 */
Mathias Agopianab028732010-03-16 16:41:46 -07002520 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002521 const Region oldVisibleRegion = layer->visibleRegion;
2522 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002523 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2524 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002525 }
2526 dirty.subtractSelf(aboveOpaqueLayers);
2527
2528 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002529 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002530
Mathias Agopianab028732010-03-16 16:41:46 -07002531 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002532 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002533
Jesse Halla8026d22012-09-25 13:25:04 -07002534 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002535 layer->setVisibleRegion(visibleRegion);
2536 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002537 layer->setVisibleNonTransparentRegion(
2538 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002539 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002540
Mathias Agopian87baae12012-07-31 12:38:26 -07002541 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002542}
2543
Chia-I Wuab0c3192017-08-01 11:29:00 -07002544void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002545 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002546 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002547 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002548 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002549 }
2550 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002551}
2552
Dan Stoza6b9454d2014-11-07 16:00:59 -08002553bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002555 ALOGV("handlePageFlip");
2556
Brian Andersond6927fb2016-07-23 23:37:30 -07002557 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558
Mathias Agopian4fec8732012-06-29 14:12:52 -07002559 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002560 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002561 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002562
2563 // Store the set of layers that need updates. This set must not change as
2564 // buffers are being latched, as this could result in a deadlock.
2565 // Example: Two producers share the same command stream and:
2566 // 1.) Layer 0 is latched
2567 // 2.) Layer 0 gets a new frame
2568 // 2.) Layer 1 gets a new frame
2569 // 3.) Layer 1 is latched.
2570 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2571 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002572 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002573 if (layer->hasQueuedFrame()) {
2574 frameQueued = true;
2575 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002576 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002577 } else {
2578 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002579 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002580 } else {
2581 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002582 }
Robert Carr2047fae2016-11-28 14:09:09 -08002583 });
2584
Dan Stoza9e56aa02015-11-02 13:00:03 -08002585 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002586 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002587 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002588 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002589 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002590 newDataLatched = true;
2591 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002592 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002593
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002594 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002595
2596 // If we will need to wake up at some time in the future to deal with a
2597 // queued frame that shouldn't be displayed during this vsync period, wake
2598 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002599 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002600 signalLayerUpdate();
2601 }
2602
2603 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002604 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605}
2606
Mathias Agopianad456f92011-01-13 17:53:01 -08002607void SurfaceFlinger::invalidateHwcGeometry()
2608{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002609 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002610}
2611
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002612
Fabien Sanglard830b8472016-11-30 16:35:58 -08002613void SurfaceFlinger::doDisplayComposition(
2614 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002615 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616{
Dan Stoza71433162014-02-04 16:22:36 -08002617 // We only need to actually compose the display if:
2618 // 1) It is being handled by hardware composer, which may need this to
2619 // keep its virtual display state machine in sync, or
2620 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002621 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002622 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002623 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002624 return;
2625 }
2626
Dan Stoza9e56aa02015-11-02 13:00:03 -08002627 ALOGV("doDisplayComposition");
2628
Mathias Agopian87baae12012-07-31 12:38:26 -07002629 Region dirtyRegion(inDirtyRegion);
2630
Mathias Agopianb8a55602009-06-26 19:06:36 -07002631 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002632 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633
Fabien Sanglard830b8472016-11-30 16:35:58 -08002634 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002635 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002636 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2637 // takes a rectangle, we must make sure to update that whole
2638 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002639 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002640 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002641 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002642 // We need to redraw the rectangle that will be updated
2643 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002644 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002645 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002646 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002647 } else {
2648 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002649 dirtyRegion.set(displayDevice->bounds());
2650 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651 }
2652 }
2653
Fabien Sanglard830b8472016-11-30 16:35:58 -08002654 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002655
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002656 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002657 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002658
2659 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002660 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661}
2662
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663bool SurfaceFlinger::doComposeSurfaces(
2664 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002665{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002666 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002667
Dan Stoza9e56aa02015-11-02 13:00:03 -08002668 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002669
2670 mat4 oldColorMatrix;
2671 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2672 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2673 if (applyColorMatrix) {
2674 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2675 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2676 }
2677
Dan Stoza9e56aa02015-11-02 13:00:03 -08002678 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2679 if (hasClientComposition) {
2680 ALOGV("hasClientComposition");
2681
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002682#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002683 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002684 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002685#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002686 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002687 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002688 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002689 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002690
2691 // |mStateLock| not needed as we are on the main thread
2692 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002693 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2694 }
2695 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002696 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002697
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002698 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002699 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2700 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002701 // when using overlays, we assume a fully transparent framebuffer
2702 // NOTE: we could reduce how much we need to clear, for instance
2703 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002704 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002705 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002706 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002707 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002708 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002709 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002710
2711 // we remove the scissor part
2712 // we're left with the letterbox region
2713 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002714 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002715
2716 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002717 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002718
2719 // but limit it to the dirty region
2720 region.andSelf(dirty);
2721
Mathias Agopianb9494d52012-04-18 02:28:45 -07002722 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002723 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002724 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002725 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002726 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002727 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002728
Dan Stoza9e56aa02015-11-02 13:00:03 -08002729 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002730 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002731 // scissor on the main display. It should never be needed
2732 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002733 const Rect& bounds(displayDevice->getBounds());
2734 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002735 if (scissor != bounds) {
2736 // scissor doesn't match the screen's dimensions, so we
2737 // need to clear everything outside of it and enable
2738 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002739
Mathias Agopianf45c5102012-10-24 16:29:17 -07002740 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002741 const uint32_t height = displayDevice->getHeight();
2742 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002743 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002744 }
2745 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002746 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002747
Mathias Agopian85d751c2012-08-29 16:59:24 -07002748 /*
2749 * and then, render the layers targeted at the framebuffer
2750 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002751
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 ALOGV("Rendering client layers");
2753 const Transform& displayTransform = displayDevice->getTransform();
2754 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002755 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002756 bool firstLayer = true;
2757 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2758 const Region clip(dirty.intersect(
2759 displayTransform.transform(layer->visibleRegion)));
2760 ALOGV("Layer: %s", layer->getName().string());
2761 ALOGV(" Composition type: %s",
2762 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002763 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002764 switch (layer->getCompositionType(hwcId)) {
2765 case HWC2::Composition::Cursor:
2766 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002767 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002768 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002769 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002770 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2771 layer->isOpaque(state) && (state.alpha == 1.0f)
2772 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002773 // never clear the very first layer since we're
2774 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002775 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002776 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002777 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002778 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002779 case HWC2::Composition::Client: {
2780 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002781 break;
2782 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002783 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002784 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002785 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002786 } else {
2787 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002788 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002789 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002790 }
2791 } else {
2792 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002793 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002794 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002795 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002796 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002797 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002798 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002799 }
2800 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002801
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002802 if (applyColorMatrix) {
2803 getRenderEngine().setupColorTransform(oldColorMatrix);
2804 }
2805
Mathias Agopianf45c5102012-10-24 16:29:17 -07002806 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002807 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002808 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809}
2810
Fabien Sanglard830b8472016-11-30 16:35:58 -08002811void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2812 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002813 RenderEngine& engine(getRenderEngine());
2814 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815}
2816
Dan Stoza7d89d062015-04-30 13:29:25 -07002817status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002818 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002819 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002820 const sp<Layer>& lbc,
2821 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002822{
Dan Stoza7d89d062015-04-30 13:29:25 -07002823 // add this layer to the current state list
2824 {
2825 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002826 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002827 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2828 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002829 return NO_MEMORY;
2830 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002831 if (parent == nullptr) {
2832 mCurrentState.layersSortedByZ.add(lbc);
2833 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002834 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2835 ALOGE("addClientLayer called with a removed parent");
2836 return NAME_NOT_FOUND;
2837 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002838 parent->addChild(lbc);
2839 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002840
Dan Stoza7d89d062015-04-30 13:29:25 -07002841 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002842 mLayersAdded = true;
2843 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002844 }
2845
Mathias Agopian96f08192010-06-02 23:28:45 -07002846 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002847 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002848
Dan Stoza7d89d062015-04-30 13:29:25 -07002849 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002850}
2851
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002852status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002853 Mutex::Autolock _l(mStateLock);
2854
Robert Carr1f0a16a2016-10-24 16:27:39 -07002855 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002856 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002857 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002858 if (topLevelOnly) {
2859 return NO_ERROR;
2860 }
2861
Chia-I Wu98f1c102017-05-30 14:54:08 -07002862 sp<Layer> ancestor = p;
2863 while (ancestor->getParent() != nullptr) {
2864 ancestor = ancestor->getParent();
2865 }
2866 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2867 ALOGE("removeLayer called with a layer whose parent has been removed");
2868 return NAME_NOT_FOUND;
2869 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002870
2871 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002872 } else {
2873 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002874 }
2875
Robert Carr136e2f62017-02-08 17:54:29 -08002876 // As a matter of normal operation, the LayerCleaner will produce a second
2877 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2878 // so we will succeed in promoting it, but it's already been removed
2879 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2880 // otherwise something has gone wrong and we are leaking the layer.
2881 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002882 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2883 layer->getName().string(),
2884 (p != nullptr) ? p->getName().string() : "no-parent");
2885 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002886 } else if (index < 0) {
2887 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002888 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002889
Chia-I Wuc6657022017-08-15 11:18:17 -07002890 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002891 mLayersPendingRemoval.add(layer);
2892 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002893 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002894 setTransactionFlags(eTransactionNeeded);
2895 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896}
2897
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002898uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002899 return android_atomic_release_load(&mTransactionFlags);
2900}
2901
Mathias Agopian3f844832013-08-07 21:24:32 -07002902uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002903 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2904}
2905
Mathias Agopian3f844832013-08-07 21:24:32 -07002906uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2908 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002909 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910 }
2911 return old;
2912}
2913
Mathias Agopian8b33f032012-07-24 20:43:54 -07002914void SurfaceFlinger::setTransactionState(
2915 const Vector<ComposerState>& state,
2916 const Vector<DisplayState>& displays,
2917 uint32_t flags)
2918{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002919 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002920 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002921 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002922
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002923 if (flags & eAnimation) {
2924 // For window updates that are part of an animation we must wait for
2925 // previous animation "frames" to be handled.
2926 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002927 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002928 if (CC_UNLIKELY(err != NO_ERROR)) {
2929 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002930 // caller after a few seconds.
2931 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2932 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002933 mAnimTransactionPending = false;
2934 break;
2935 }
2936 }
2937 }
2938
Mathias Agopiane57f2922012-08-09 16:29:12 -07002939 size_t count = displays.size();
2940 for (size_t i=0 ; i<count ; i++) {
2941 const DisplayState& s(displays[i]);
2942 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002943 }
2944
Mathias Agopiane57f2922012-08-09 16:29:12 -07002945 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002946 for (size_t i=0 ; i<count ; i++) {
2947 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002948 // Here we need to check that the interface we're given is indeed
2949 // one of our own. A malicious client could give us a NULL
2950 // IInterface, or one of its own or even one of our own but a
2951 // different type. All these situations would cause us to crash.
2952 //
2953 // NOTE: it would be better to use RTTI as we could directly check
2954 // that we have a Client*. however, RTTI is disabled in Android.
2955 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002956 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002957 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002958 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002959 sp<Client> client( static_cast<Client *>(s.client.get()) );
2960 transactionFlags |= setClientStateLocked(client, s.state);
2961 }
2962 }
2963 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002964 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002965
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002966 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2967 // anyway. This can be used as a flush mechanism for previous async transactions.
2968 // Empty animation transaction can be used to simulate back-pressure, so also force a
2969 // transaction for empty animation transactions.
2970 if (transactionFlags == 0 &&
2971 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002972 transactionFlags = eTransactionNeeded;
2973 }
2974
Mathias Agopian386aa982011-11-07 21:58:03 -08002975 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002976 if (mInterceptor.isEnabled()) {
2977 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2978 }
Irvel468051e2016-06-13 16:44:44 -07002979
Mathias Agopian386aa982011-11-07 21:58:03 -08002980 // this triggers the transaction
2981 setTransactionFlags(transactionFlags);
2982
2983 // if this is a synchronous transaction, wait for it to take effect
2984 // before returning.
2985 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002986 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002987 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002988 if (flags & eAnimation) {
2989 mAnimTransactionPending = true;
2990 }
2991 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002992 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2993 if (CC_UNLIKELY(err != NO_ERROR)) {
2994 // just in case something goes wrong in SF, return to the
2995 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002996 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2997 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002998 break;
2999 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003000 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003001 }
3002}
3003
Mathias Agopiane57f2922012-08-09 16:29:12 -07003004uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3005{
Jesse Hall9a143922012-10-04 16:29:19 -07003006 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3007 if (dpyIdx < 0)
3008 return 0;
3009
Mathias Agopiane57f2922012-08-09 16:29:12 -07003010 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003011 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003012 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003013 const uint32_t what = s.what;
3014 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003015 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003016 disp.surface = s.surface;
3017 flags |= eDisplayTransactionNeeded;
3018 }
3019 }
3020 if (what & DisplayState::eLayerStackChanged) {
3021 if (disp.layerStack != s.layerStack) {
3022 disp.layerStack = s.layerStack;
3023 flags |= eDisplayTransactionNeeded;
3024 }
3025 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003026 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003027 if (disp.orientation != s.orientation) {
3028 disp.orientation = s.orientation;
3029 flags |= eDisplayTransactionNeeded;
3030 }
3031 if (disp.frame != s.frame) {
3032 disp.frame = s.frame;
3033 flags |= eDisplayTransactionNeeded;
3034 }
3035 if (disp.viewport != s.viewport) {
3036 disp.viewport = s.viewport;
3037 flags |= eDisplayTransactionNeeded;
3038 }
3039 }
Michael Lentine47e45402014-07-18 15:34:25 -07003040 if (what & DisplayState::eDisplaySizeChanged) {
3041 if (disp.width != s.width) {
3042 disp.width = s.width;
3043 flags |= eDisplayTransactionNeeded;
3044 }
3045 if (disp.height != s.height) {
3046 disp.height = s.height;
3047 flags |= eDisplayTransactionNeeded;
3048 }
3049 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003050 }
3051 return flags;
3052}
3053
3054uint32_t SurfaceFlinger::setClientStateLocked(
3055 const sp<Client>& client,
3056 const layer_state_t& s)
3057{
3058 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003059 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003060 if (layer != 0) {
3061 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003062 bool geometryAppliesWithResize =
3063 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003064 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003065 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003066 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003067 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003068 }
3069 if (what & layer_state_t::eLayerChanged) {
3070 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003071 const auto& p = layer->getParent();
3072 if (p == nullptr) {
3073 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3074 if (layer->setLayer(s.z) && idx >= 0) {
3075 mCurrentState.layersSortedByZ.removeAt(idx);
3076 mCurrentState.layersSortedByZ.add(layer);
3077 // we need traversal (state changed)
3078 // AND transaction (list changed)
3079 flags |= eTransactionNeeded|eTraversalNeeded;
3080 }
3081 } else {
3082 if (p->setChildLayer(layer, s.z)) {
3083 flags |= eTransactionNeeded|eTraversalNeeded;
3084 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003085 }
3086 }
Robert Carrdb66e622017-04-10 16:55:57 -07003087 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003088 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003089 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003090 mCurrentState.layersSortedByZ.removeAt(idx);
3091 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003092 flags |= eTransactionNeeded|eTraversalNeeded;
3093 }
3094 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003095 if (what & layer_state_t::eSizeChanged) {
3096 if (layer->setSize(s.w, s.h)) {
3097 flags |= eTraversalNeeded;
3098 }
3099 }
3100 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003101 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003102 flags |= eTraversalNeeded;
3103 }
3104 if (what & layer_state_t::eMatrixChanged) {
3105 if (layer->setMatrix(s.matrix))
3106 flags |= eTraversalNeeded;
3107 }
3108 if (what & layer_state_t::eTransparentRegionChanged) {
3109 if (layer->setTransparentRegionHint(s.transparentRegion))
3110 flags |= eTraversalNeeded;
3111 }
Dan Stoza23116082015-06-18 14:58:39 -07003112 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003113 if (layer->setFlags(s.flags, s.mask))
3114 flags |= eTraversalNeeded;
3115 }
3116 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003117 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003118 flags |= eTraversalNeeded;
3119 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003120 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003121 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003122 flags |= eTraversalNeeded;
3123 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003124 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003125 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003126 // We only allow setting layer stacks for top level layers,
3127 // everything else inherits layer stack from its parent.
3128 if (layer->hasParent()) {
3129 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3130 layer->getName().string());
3131 } else if (idx < 0) {
3132 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3133 "that also does not appear in the top level layer list. Something"
3134 " has gone wrong.", layer->getName().string());
3135 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003136 mCurrentState.layersSortedByZ.removeAt(idx);
3137 mCurrentState.layersSortedByZ.add(layer);
3138 // we need traversal (state changed)
3139 // AND transaction (list changed)
3140 flags |= eTransactionNeeded|eTraversalNeeded;
3141 }
3142 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003143 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003144 if (s.barrierHandle != nullptr) {
3145 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3146 } else if (s.barrierGbp != nullptr) {
3147 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3148 if (authenticateSurfaceTextureLocked(gbp)) {
3149 const auto& otherLayer =
3150 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3151 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3152 } else {
3153 ALOGE("Attempt to defer transaction to to an"
3154 " unrecognized GraphicBufferProducer");
3155 }
3156 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003157 // We don't trigger a traversal here because if no other state is
3158 // changed, we don't want this to cause any more work
3159 }
Robert Carr1db73f62016-12-21 12:58:51 -08003160 if (what & layer_state_t::eReparentChildren) {
3161 if (layer->reparentChildren(s.reparentHandle)) {
3162 flags |= eTransactionNeeded|eTraversalNeeded;
3163 }
3164 }
Robert Carr9524cb32017-02-13 11:32:32 -08003165 if (what & layer_state_t::eDetachChildren) {
3166 layer->detachChildren();
3167 }
Robert Carrc3574f72016-03-24 12:19:32 -07003168 if (what & layer_state_t::eOverrideScalingModeChanged) {
3169 layer->setOverrideScalingMode(s.overrideScalingMode);
3170 // We don't trigger a traversal here because if no other state is
3171 // changed, we don't want this to cause any more work
3172 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003173 }
3174 return flags;
3175}
3176
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003177status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003178 const String8& name,
3179 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003180 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003181 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3182 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003183{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003184 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003185 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003186 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003187 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003188 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003189
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003190 status_t result = NO_ERROR;
3191
3192 sp<Layer> layer;
3193
Cody Northropbc755282017-03-31 12:00:08 -06003194 String8 uniqueName = getUniqueLayerName(name);
3195
Mathias Agopian3165cc22012-08-08 19:42:09 -07003196 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3197 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003198 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003199 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003200 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003202 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003203 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003204 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003205 handle, gbp, &layer);
3206 break;
3207 default:
3208 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003209 break;
3210 }
3211
Dan Stoza7d89d062015-04-30 13:29:25 -07003212 if (result != NO_ERROR) {
3213 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003215
Chia-I Wuab0c3192017-08-01 11:29:00 -07003216 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3217 // TODO b/64227542
3218 if (windowType == 441731) {
3219 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3220 layer->setPrimaryDisplayOnly();
3221 }
3222
Albert Chaulk479c60c2017-01-27 14:21:34 -05003223 layer->setInfo(windowType, ownerUid);
3224
Robert Carr1f0a16a2016-10-24 16:27:39 -07003225 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003226 if (result != NO_ERROR) {
3227 return result;
3228 }
Irvelffc9efc2016-07-27 15:16:37 -07003229 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003230
3231 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003232 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233}
3234
Cody Northropbc755282017-03-31 12:00:08 -06003235String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3236{
3237 bool matchFound = true;
3238 uint32_t dupeCounter = 0;
3239
3240 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3241 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3242
3243 // Loop over layers until we're sure there is no matching name
3244 while (matchFound) {
3245 matchFound = false;
3246 mDrawingState.traverseInZOrder([&](Layer* layer) {
3247 if (layer->getName() == uniqueName) {
3248 matchFound = true;
3249 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3250 }
3251 });
3252 }
3253
3254 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3255
3256 return uniqueName;
3257}
3258
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003259status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3260 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3261 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262{
3263 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003264 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265 case PIXEL_FORMAT_TRANSPARENT:
3266 case PIXEL_FORMAT_TRANSLUCENT:
3267 format = PIXEL_FORMAT_RGBA_8888;
3268 break;
3269 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003270 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003271 break;
3272 }
3273
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003274 *outLayer = new Layer(this, client, name, w, h, flags);
3275 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3276 if (err == NO_ERROR) {
3277 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003278 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003279 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003280
3281 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3282 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283}
3284
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003285status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3286 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3287 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003288{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003289 *outLayer = new LayerDim(this, client, name, w, h, flags);
3290 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003291 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003292 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003293}
3294
Mathias Agopianac9fa422013-02-11 16:40:36 -08003295status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296{
Robert Carr9524cb32017-02-13 11:32:32 -08003297 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003298 status_t err = NO_ERROR;
3299 sp<Layer> l(client->getLayerUser(handle));
3300 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003301 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003302 err = removeLayer(l);
3303 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3304 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003305 }
3306 return err;
3307}
3308
Mathias Agopian13127d82013-03-05 17:47:11 -08003309status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003310{
Mathias Agopian67106042013-03-14 19:18:13 -07003311 // called by ~LayerCleaner() when all references to the IBinder (handle)
3312 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003313 sp<Layer> l = layer.promote();
3314 if (l == nullptr) {
3315 // The layer has already been removed, carry on
3316 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003317 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003318 // If we have a parent, then we can continue to live as long as it does.
3319 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003320}
3321
Mathias Agopianb60314a2012-04-10 22:09:54 -07003322// ---------------------------------------------------------------------------
3323
Andy McFadden13a082e2012-08-24 10:16:42 -07003324void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003325 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003326 Vector<ComposerState> state;
3327 Vector<DisplayState> displays;
3328 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003329 d.what = DisplayState::eDisplayProjectionChanged |
3330 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003331 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003332 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003333 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003334 d.frame.makeInvalid();
3335 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003336 d.width = 0;
3337 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003338 displays.add(d);
3339 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003340 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3341 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003342
Dan Stoza9e56aa02015-11-02 13:00:03 -08003343 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3344 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003345 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003346
Brian Andersond0010582017-03-07 13:20:31 -08003347 // Use phase of 0 since phase is not known.
3348 // Use latency of 0, which will snap to the ideal latency.
3349 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003350}
3351
3352void SurfaceFlinger::initializeDisplays() {
3353 class MessageScreenInitialized : public MessageBase {
3354 SurfaceFlinger* flinger;
3355 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003356 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003357 virtual bool handler() {
3358 flinger->onInitializeDisplays();
3359 return true;
3360 }
3361 };
3362 sp<MessageBase> msg = new MessageScreenInitialized(this);
3363 postMessageAsync(msg); // we may be called from main thread, use async message
3364}
3365
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003366void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003367 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003368 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3369 this);
3370 int32_t type = hw->getDisplayType();
3371 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003372
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003373 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003374 return;
3375 }
3376
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003377 hw->setPowerMode(mode);
3378 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3379 ALOGW("Trying to set power mode for virtual display");
3380 return;
3381 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003382
Irvelffc9efc2016-07-27 15:16:37 -07003383 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003384 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003385 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3386 if (idx < 0) {
3387 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3388 return;
3389 }
3390 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3391 }
3392
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003393 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003394 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003395 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003396 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3397 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003398 // FIXME: eventthread only knows about the main display right now
3399 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003400 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003401 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003402
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003403 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003404 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003405 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003406
3407 struct sched_param param = {0};
3408 param.sched_priority = 1;
3409 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3410 ALOGW("Couldn't set SCHED_FIFO on display on");
3411 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003412 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003413 // Turn off the display
3414 struct sched_param param = {0};
3415 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3416 ALOGW("Couldn't set SCHED_OTHER on display off");
3417 }
3418
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003419 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003420 disableHardwareVsync(true); // also cancels any in-progress resync
3421
Mathias Agopiancde87a32012-09-13 14:09:01 -07003422 // FIXME: eventthread only knows about the main display right now
3423 mEventThread->onScreenReleased();
3424 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003425
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003426 getHwComposer().setPowerMode(type, mode);
3427 mVisibleRegionsDirty = true;
3428 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003429 } else if (mode == HWC_POWER_MODE_DOZE ||
3430 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003431 // Update display while dozing
3432 getHwComposer().setPowerMode(type, mode);
3433 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3434 // FIXME: eventthread only knows about the main display right now
3435 mEventThread->onScreenAcquired();
3436 resyncToHardwareVsync(true);
3437 }
3438 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3439 // Leave display going to doze
3440 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3441 disableHardwareVsync(true); // also cancels any in-progress resync
3442 // FIXME: eventthread only knows about the main display right now
3443 mEventThread->onScreenReleased();
3444 }
3445 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003446 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003447 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003448 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003449 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003450}
3451
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003452void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3453 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003454 SurfaceFlinger& mFlinger;
3455 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003456 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003457 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003458 MessageSetPowerMode(SurfaceFlinger& flinger,
3459 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3460 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003461 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003462 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003463 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003464 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003465 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003466 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003467 ALOGW("Attempt to set power mode = %d for virtual display",
3468 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003469 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003470 mFlinger.setPowerModeInternal(
3471 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003472 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003473 return true;
3474 }
3475 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003476 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003477 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003478}
3479
3480// ---------------------------------------------------------------------------
3481
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003482status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3483{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003484 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003485
Mathias Agopianbd115332013-04-18 16:41:04 -07003486 IPCThreadState* ipc = IPCThreadState::self();
3487 const int pid = ipc->getCallingPid();
3488 const int uid = ipc->getCallingUid();
3489 if ((uid != AID_SHELL) &&
3490 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003491 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003492 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003493 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003494 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003495 // (this would indicate SF is stuck, but we want to be able to
3496 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003497 status_t err = mStateLock.timedLock(s2ns(1));
3498 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003499 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003500 result.appendFormat(
3501 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3502 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003503 }
3504
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003505 bool dumpAll = true;
3506 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003507 size_t numArgs = args.size();
3508 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003509 if ((index < numArgs) &&
3510 (args[index] == String16("--list"))) {
3511 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003512 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003513 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003514 }
3515
3516 if ((index < numArgs) &&
3517 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003518 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003519 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003520 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003521 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003522
3523 if ((index < numArgs) &&
3524 (args[index] == String16("--latency-clear"))) {
3525 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003526 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003527 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003528 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003529
3530 if ((index < numArgs) &&
3531 (args[index] == String16("--dispsync"))) {
3532 index++;
3533 mPrimaryDispSync.dump(result);
3534 dumpAll = false;
3535 }
Dan Stozab90cf072015-03-05 11:05:59 -08003536
3537 if ((index < numArgs) &&
3538 (args[index] == String16("--static-screen"))) {
3539 index++;
3540 dumpStaticScreenStats(result);
3541 dumpAll = false;
3542 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003543
3544 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003545 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003546 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003547 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003548 dumpAll = false;
3549 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003550
3551 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3552 index++;
3553 dumpWideColorInfo(result);
3554 dumpAll = false;
3555 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003556 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003557
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003558 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003559 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003560 }
3561
Mathias Agopian9795c422009-08-26 16:36:26 -07003562 if (locked) {
3563 mStateLock.unlock();
3564 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003565 }
3566 write(fd, result.string(), result.size());
3567 return NO_ERROR;
3568}
3569
Dan Stozac7014012014-02-14 15:03:43 -08003570void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3571 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003572{
Robert Carr2047fae2016-11-28 14:09:09 -08003573 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003574 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003575 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003576}
3577
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003578void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003579 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003580{
3581 String8 name;
3582 if (index < args.size()) {
3583 name = String8(args[index]);
3584 index++;
3585 }
3586
Dan Stoza9e56aa02015-11-02 13:00:03 -08003587 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3588 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003589 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003590
3591 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003592 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003593 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003594 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003595 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003596 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003597 }
Robert Carr2047fae2016-11-28 14:09:09 -08003598 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003599 }
3600}
3601
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003602void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003603 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003604{
3605 String8 name;
3606 if (index < args.size()) {
3607 name = String8(args[index]);
3608 index++;
3609 }
3610
Robert Carr2047fae2016-11-28 14:09:09 -08003611 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003612 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003613 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003614 }
Robert Carr2047fae2016-11-28 14:09:09 -08003615 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003616
Svetoslavd85084b2014-03-20 10:28:31 -07003617 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003618}
3619
Jamie Gennis6547ff42013-07-16 20:12:42 -07003620// This should only be called from the main thread. Otherwise it would need
3621// the lock and should use mCurrentState rather than mDrawingState.
3622void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003623 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003624 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003625 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003626
3627 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3628}
3629
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003630void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003631{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003632 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003633 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3634
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003635 if (isLayerTripleBufferingDisabled())
3636 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003637
3638 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003639 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003640 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003641 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003642 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3643 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003644 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003645}
3646
Dan Stozab90cf072015-03-05 11:05:59 -08003647void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3648{
3649 result.appendFormat("Static screen stats:\n");
3650 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3651 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3652 float percent = 100.0f *
3653 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3654 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3655 b + 1, bucketTimeSec, percent);
3656 }
3657 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3658 float percent = 100.0f *
3659 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3660 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3661 NUM_BUCKETS - 1, bucketTimeSec, percent);
3662}
3663
Dan Stozae77c7662016-05-13 11:37:28 -07003664void SurfaceFlinger::recordBufferingStats(const char* layerName,
3665 std::vector<OccupancyTracker::Segment>&& history) {
3666 Mutex::Autolock lock(mBufferingStatsMutex);
3667 auto& stats = mBufferingStats[layerName];
3668 for (const auto& segment : history) {
3669 if (!segment.usedThirdBuffer) {
3670 stats.twoBufferTime += segment.totalTime;
3671 }
3672 if (segment.occupancyAverage < 1.0f) {
3673 stats.doubleBufferedTime += segment.totalTime;
3674 } else if (segment.occupancyAverage < 2.0f) {
3675 stats.tripleBufferedTime += segment.totalTime;
3676 }
3677 ++stats.numSegments;
3678 stats.totalTime += segment.totalTime;
3679 }
3680}
3681
Brian Andersond6927fb2016-07-23 23:37:30 -07003682void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3683 result.appendFormat("Layer frame timestamps:\n");
3684
3685 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3686 const size_t count = currentLayers.size();
3687 for (size_t i=0 ; i<count ; i++) {
3688 currentLayers[i]->dumpFrameEvents(result);
3689 }
3690}
3691
Dan Stozae77c7662016-05-13 11:37:28 -07003692void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3693 result.append("Buffering stats:\n");
3694 result.append(" [Layer name] <Active time> <Two buffer> "
3695 "<Double buffered> <Triple buffered>\n");
3696 Mutex::Autolock lock(mBufferingStatsMutex);
3697 typedef std::tuple<std::string, float, float, float> BufferTuple;
3698 std::map<float, BufferTuple, std::greater<float>> sorted;
3699 for (const auto& statsPair : mBufferingStats) {
3700 const char* name = statsPair.first.c_str();
3701 const BufferingStats& stats = statsPair.second;
3702 if (stats.numSegments == 0) {
3703 continue;
3704 }
3705 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3706 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3707 stats.totalTime;
3708 float doubleBufferRatio = static_cast<float>(
3709 stats.doubleBufferedTime) / stats.totalTime;
3710 float tripleBufferRatio = static_cast<float>(
3711 stats.tripleBufferedTime) / stats.totalTime;
3712 sorted.insert({activeTime, {name, twoBufferRatio,
3713 doubleBufferRatio, tripleBufferRatio}});
3714 }
3715 for (const auto& sortedPair : sorted) {
3716 float activeTime = sortedPair.first;
3717 const BufferTuple& values = sortedPair.second;
3718 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3719 std::get<0>(values).c_str(), activeTime,
3720 std::get<1>(values), std::get<2>(values),
3721 std::get<3>(values));
3722 }
3723 result.append("\n");
3724}
3725
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003726void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3727 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3728
3729 // TODO: print out if wide-color mode is active or not
3730
3731 for (size_t d = 0; d < mDisplays.size(); d++) {
3732 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3733 int32_t hwcId = displayDevice->getHwcDisplayId();
3734 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3735 continue;
3736 }
3737
3738 result.appendFormat("Display %d color modes:\n", hwcId);
3739 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3740 for (auto&& mode : modes) {
3741 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3742 }
3743
3744 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3745 result.appendFormat(" Current color mode: %s (%d)\n",
3746 decodeColorMode(currentMode).c_str(), currentMode);
3747 }
3748 result.append("\n");
3749}
3750
Mathias Agopian74d211a2013-04-22 16:55:35 +02003751void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3752 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003753{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003754 bool colorize = false;
3755 if (index < args.size()
3756 && (args[index] == String16("--color"))) {
3757 colorize = true;
3758 index++;
3759 }
3760
3761 Colorizer colorizer(colorize);
3762
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003763 // figure out if we're stuck somewhere
3764 const nsecs_t now = systemTime();
3765 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3766 const nsecs_t inTransaction(mDebugInTransaction);
3767 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3768 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3769
3770 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003771 * Dump library configuration.
3772 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003773
3774 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003775 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003776 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003777 appendSfConfigString(result);
3778 appendUiConfigString(result);
3779 appendGuiConfigString(result);
3780 result.append("\n");
3781
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003782 result.append("\nWide-Color information:\n");
3783 dumpWideColorInfo(result);
3784
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003785 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003786 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003787 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003788 result.append(SyncFeatures::getInstance().toString());
3789 result.append("\n");
3790
Dan Stoza9e56aa02015-11-02 13:00:03 -08003791 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3792
Andy McFadden41d67d72014-04-25 16:58:34 -07003793 colorizer.bold(result);
3794 result.append("DispSync configuration: ");
3795 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003796 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003797 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003798 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003799 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003800 result.append("\n");
3801
Dan Stozab90cf072015-03-05 11:05:59 -08003802 // Dump static screen stats
3803 result.append("\n");
3804 dumpStaticScreenStats(result);
3805 result.append("\n");
3806
Dan Stozae77c7662016-05-13 11:37:28 -07003807 dumpBufferingStats(result);
3808
Andy McFadden4803b742012-09-24 19:07:20 -07003809 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003810 * Dump the visible layer list
3811 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003812 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003813 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003814 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003815 mCurrentState.traverseInZOrder([&](Layer* layer) {
Kalle Raitaa099a242017-01-11 11:17:29 -08003816 result.append(to_string(layer->getLayerDebugInfo()).c_str());
Robert Carr2047fae2016-11-28 14:09:09 -08003817 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003818
3819 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003820 * Dump Display state
3821 */
3822
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003823 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003824 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003825 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003826 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3827 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003828 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003829 }
3830
3831 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003832 * Dump SurfaceFlinger global state
3833 */
3834
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003835 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003836 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003837 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003838
Mathias Agopian888c8222012-08-04 21:10:38 -07003839 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003840 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003841
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003842 colorizer.bold(result);
3843 result.appendFormat("EGL implementation : %s\n",
3844 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3845 colorizer.reset(result);
3846 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003847 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003848
Mathias Agopian875d8e12013-06-07 15:35:48 -07003849 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003850
Mathias Agopian42977342012-08-05 00:40:46 -07003851 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003852 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3853 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003854 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003855 " last eglSwapBuffers() time: %f us\n"
3856 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003857 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003858 " refresh-rate : %f fps\n"
3859 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003860 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003861 " gpu_to_cpu_unsupported : %d\n"
3862 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003863 mLastSwapBufferTime/1000.0,
3864 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003865 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003866 1e9 / activeConfig->getVsyncPeriod(),
3867 activeConfig->getDpiX(),
3868 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003869 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003870
Mathias Agopian74d211a2013-04-22 16:55:35 +02003871 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003872 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003873
Mathias Agopian74d211a2013-04-22 16:55:35 +02003874 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003875 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003876
3877 /*
3878 * VSYNC state
3879 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003880 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003881 result.append("\n");
3882
3883 /*
3884 * HWC layer minidump
3885 */
3886 for (size_t d = 0; d < mDisplays.size(); d++) {
3887 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3888 int32_t hwcId = displayDevice->getHwcDisplayId();
3889 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3890 continue;
3891 }
3892
3893 result.appendFormat("Display %d HWC layers:\n", hwcId);
3894 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003895 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003896 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003897 });
Dan Stozae22aec72016-08-01 13:20:59 -07003898 result.append("\n");
3899 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003900
3901 /*
3902 * Dump HWComposer state
3903 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003904 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003905 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003906 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003907 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003908 result.appendFormat(" h/w composer %s\n",
3909 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003910 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003911
3912 /*
3913 * Dump gralloc state
3914 */
3915 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3916 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003917
3918 /*
3919 * Dump VrFlinger state if in use.
3920 */
3921 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3922 result.append("VrFlinger state:\n");
3923 result.append(mVrFlinger->Dump().c_str());
3924 result.append("\n");
3925 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003926}
3927
Mathias Agopian13127d82013-03-05 17:47:11 -08003928const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003929SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003930 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003931 wp<IBinder> dpy;
3932 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3933 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3934 dpy = mDisplays.keyAt(i);
3935 break;
3936 }
3937 }
3938 if (dpy == NULL) {
3939 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3940 // Just use the primary display so we have something to return
3941 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3942 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003943 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003944}
3945
Keun young Park63f165f2012-08-31 10:53:36 -07003946bool SurfaceFlinger::startDdmConnection()
3947{
3948 void* libddmconnection_dso =
3949 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3950 if (!libddmconnection_dso) {
3951 return false;
3952 }
3953 void (*DdmConnection_start)(const char* name);
3954 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003955 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003956 if (!DdmConnection_start) {
3957 dlclose(libddmconnection_dso);
3958 return false;
3959 }
3960 (*DdmConnection_start)(getServiceName());
3961 return true;
3962}
3963
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003964status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003965 switch (code) {
3966 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003967 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003968 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003969 case CLEAR_ANIMATION_FRAME_STATS:
3970 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003971 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003972 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003973 {
3974 // codes that require permission check
3975 IPCThreadState* ipc = IPCThreadState::self();
3976 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003977 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003978 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003979 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003980 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003981 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003982 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003983 break;
3984 }
Robert Carr1db73f62016-12-21 12:58:51 -08003985 /*
3986 * Calling setTransactionState is safe, because you need to have been
3987 * granted a reference to Client* and Handle* to do anything with it.
3988 *
3989 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3990 */
3991 case SET_TRANSACTION_STATE:
3992 case CREATE_SCOPED_CONNECTION:
3993 {
3994 return OK;
3995 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003996 case CAPTURE_SCREEN:
3997 {
3998 // codes that require permission check
3999 IPCThreadState* ipc = IPCThreadState::self();
4000 const int pid = ipc->getCallingPid();
4001 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004002 if ((uid != AID_GRAPHICS) &&
4003 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004004 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004005 return PERMISSION_DENIED;
4006 }
4007 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004008 }
4009 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004010 return OK;
4011}
4012
4013status_t SurfaceFlinger::onTransact(
4014 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4015{
4016 status_t credentialCheck = CheckTransactCodeCredentials(code);
4017 if (credentialCheck != OK) {
4018 return credentialCheck;
4019 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004020
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004021 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4022 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004023 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004024 IPCThreadState* ipc = IPCThreadState::self();
4025 const int uid = ipc->getCallingUid();
4026 if (CC_UNLIKELY(uid != AID_SYSTEM
4027 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004028 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004029 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004030 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004031 return PERMISSION_DENIED;
4032 }
4033 int n;
4034 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004035 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004036 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004037 return NO_ERROR;
4038 case 1002: // SHOW_UPDATES
4039 n = data.readInt32();
4040 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004041 invalidateHwcGeometry();
4042 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004043 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004044 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004045 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004046 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004047 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004048 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004049 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004050 setTransactionFlags(
4051 eTransactionNeeded|
4052 eDisplayTransactionNeeded|
4053 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004054 return NO_ERROR;
4055 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004056 case 1006:{ // send empty update
4057 signalRefresh();
4058 return NO_ERROR;
4059 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004060 case 1008: // toggle use of hw composer
4061 n = data.readInt32();
4062 mDebugDisableHWC = n ? 1 : 0;
4063 invalidateHwcGeometry();
4064 repaintEverything();
4065 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004066 case 1009: // toggle use of transform hint
4067 n = data.readInt32();
4068 mDebugDisableTransformHint = n ? 1 : 0;
4069 invalidateHwcGeometry();
4070 repaintEverything();
4071 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004072 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004073 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004074 reply->writeInt32(0);
4075 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004076 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004077 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004078 return NO_ERROR;
4079 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004080 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004081 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004082 return NO_ERROR;
4083 }
4084 case 1014: {
4085 // daltonize
4086 n = data.readInt32();
4087 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004088 case 1:
4089 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4090 break;
4091 case 2:
4092 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4093 break;
4094 case 3:
4095 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4096 break;
4097 default:
4098 mDaltonizer.setType(ColorBlindnessType::None);
4099 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004100 }
4101 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004102 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004103 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004104 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004105 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004106 invalidateHwcGeometry();
4107 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004108 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004109 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004110 case 1015: {
4111 // apply a color matrix
4112 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004113 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004114 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004115 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004116 for (size_t j = 0; j < 4; j++) {
4117 mColorMatrix[i][j] = data.readFloat();
4118 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004119 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004120 } else {
4121 mColorMatrix = mat4();
4122 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004123
4124 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4125 // the division by w in the fragment shader
4126 float4 lastRow(transpose(mColorMatrix)[3]);
4127 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4128 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4129 }
4130
Alan Viverette9c5a3332013-09-12 20:04:35 -07004131 invalidateHwcGeometry();
4132 repaintEverything();
4133 return NO_ERROR;
4134 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004135 // This is an experimental interface
4136 // Needs to be shifted to proper binder interface when we productize
4137 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004138 n = data.readInt32();
4139 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004140 return NO_ERROR;
4141 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004142 case 1017: {
4143 n = data.readInt32();
4144 mForceFullDamage = static_cast<bool>(n);
4145 return NO_ERROR;
4146 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004147 case 1018: { // Modify Choreographer's phase offset
4148 n = data.readInt32();
4149 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4150 return NO_ERROR;
4151 }
4152 case 1019: { // Modify SurfaceFlinger's phase offset
4153 n = data.readInt32();
4154 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4155 return NO_ERROR;
4156 }
Irvel468051e2016-06-13 16:44:44 -07004157 case 1020: { // Layer updates interceptor
4158 n = data.readInt32();
4159 if (n) {
4160 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004161 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004162 }
4163 else{
4164 ALOGV("Interceptor disabled");
4165 mInterceptor.disable();
4166 }
4167 return NO_ERROR;
4168 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004169 case 1021: { // Disable HWC virtual displays
4170 n = data.readInt32();
4171 mUseHwcVirtualDisplays = !n;
4172 return NO_ERROR;
4173 }
Romain Guy0147a172017-06-01 13:53:56 -07004174 case 1022: { // Set saturation boost
4175 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4176
4177 invalidateHwcGeometry();
4178 repaintEverything();
4179 return NO_ERROR;
4180 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004181 }
4182 }
4183 return err;
4184}
4185
Steven Thomas6d8110b2017-08-31 18:24:21 -07004186void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004187 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004188 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004189}
4190
Steven Thomas6d8110b2017-08-31 18:24:21 -07004191void SurfaceFlinger::repaintEverything() {
4192 ConditionalLock _l(mStateLock,
4193 std::this_thread::get_id() != mMainThreadId);
4194 repaintEverythingLocked();
4195}
4196
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004197// Checks that the requested width and height are valid and updates them to the display dimensions
4198// if they are set to 0
4199static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4200 Transform::orientation_flags rotation,
4201 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4202 // get screen geometry
4203 uint32_t displayWidth = displayDevice->getWidth();
4204 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004205
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004206 if (rotation & Transform::ROT_90) {
4207 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004208 }
4209
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004210 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4211 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4212 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4213 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004214 }
4215
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004216 if (*requestedWidth == 0) {
4217 *requestedWidth = displayWidth;
4218 }
4219 if (*requestedHeight == 0) {
4220 *requestedHeight = displayHeight;
4221 }
4222
4223 return NO_ERROR;
4224}
4225
4226// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4227class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004228public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004229 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4230 ~WindowDisconnector() {
4231 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004232 }
4233
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004234private:
4235 ANativeWindow* mWindow;
4236 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004237};
4238
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004239static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4240 uint32_t requestedHeight, bool hasWideColorDisplay,
4241 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4242 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4243 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4244
4245 int err = 0;
4246 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4247 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4248 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4249 err |= native_window_set_usage(window, usage);
4250
4251 if (hasWideColorDisplay) {
4252 err |= native_window_set_buffers_data_space(window,
4253 renderEngineUsesWideColor
4254 ? HAL_DATASPACE_DISPLAY_P3
4255 : HAL_DATASPACE_V0_SRGB);
4256 }
4257
4258 if (err != NO_ERROR) {
4259 return BAD_VALUE;
4260 }
4261
4262 /* TODO: Once we have the sync framework everywhere this can use
4263 * server-side waits on the fence that dequeueBuffer returns.
4264 */
4265 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4266 if (err != NO_ERROR) {
4267 return err;
4268 }
4269
4270 return NO_ERROR;
4271}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004272
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004273status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4274 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004275 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004276 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004277 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004278 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004279
4280 if (CC_UNLIKELY(display == 0))
4281 return BAD_VALUE;
4282
4283 if (CC_UNLIKELY(producer == 0))
4284 return BAD_VALUE;
4285
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004286 // if we have secure windows on this display, never allow the screen capture
4287 // unless the producer interface is local (i.e.: we can take a screenshot for
4288 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004289 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004290
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004291 // Convert to surfaceflinger's internal rotation type.
4292 Transform::orientation_flags rotationFlags;
4293 switch (rotation) {
4294 case ISurfaceComposer::eRotateNone:
4295 rotationFlags = Transform::ROT_0;
4296 break;
4297 case ISurfaceComposer::eRotate90:
4298 rotationFlags = Transform::ROT_90;
4299 break;
4300 case ISurfaceComposer::eRotate180:
4301 rotationFlags = Transform::ROT_180;
4302 break;
4303 case ISurfaceComposer::eRotate270:
4304 rotationFlags = Transform::ROT_270;
4305 break;
4306 default:
4307 rotationFlags = Transform::ROT_0;
4308 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4309 break;
4310 }
4311
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004312 { // Autolock scope
4313 Mutex::Autolock lock(mStateLock);
4314 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4315 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004316 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004317
4318 // create a surface (because we're a producer, and we need to
4319 // dequeue/queue a buffer)
4320 sp<Surface> surface = new Surface(producer, false);
4321
4322 // Put the screenshot Surface into async mode so that
4323 // Layer::headFenceHasSignaled will always return true and we'll latch the
4324 // first buffer regardless of whether or not its acquire fence has
4325 // signaled. This is needed to avoid a race condition in the rotation
4326 // animation. See b/30209608
4327 surface->setAsyncMode(true);
4328
4329 ANativeWindow* window = surface.get();
4330
4331 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4332 if (result != NO_ERROR) {
4333 return result;
4334 }
4335 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4336
4337 ANativeWindowBuffer* buffer = nullptr;
4338 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4339 getRenderEngine().usesWideColor(), &buffer);
4340 if (result != NO_ERROR) {
4341 return result;
4342 }
4343
4344 // This mutex protects syncFd and captureResult for communication of the return values from the
4345 // main thread back to this Binder thread
4346 std::mutex captureMutex;
4347 std::condition_variable captureCondition;
4348 std::unique_lock<std::mutex> captureLock(captureMutex);
4349 int syncFd = -1;
4350 std::optional<status_t> captureResult;
4351
4352 sp<LambdaMessage> message = new LambdaMessage([&]() {
4353 // If there is a refresh pending, bug out early and tell the binder thread to try again
4354 // after the refresh.
4355 if (mRefreshPending) {
4356 ATRACE_NAME("Skipping screenshot for now");
4357 std::unique_lock<std::mutex> captureLock(captureMutex);
4358 captureResult = std::make_optional<status_t>(EAGAIN);
4359 captureCondition.notify_one();
4360 return;
4361 }
4362
4363 status_t result = NO_ERROR;
4364 int fd = -1;
4365 {
4366 Mutex::Autolock _l(mStateLock);
4367 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4368 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4369 minLayerZ, maxLayerZ, useIdentityTransform,
4370 rotationFlags, isLocalScreenshot, &fd);
4371 }
4372
4373 {
4374 std::unique_lock<std::mutex> captureLock(captureMutex);
4375 syncFd = fd;
4376 captureResult = std::make_optional<status_t>(result);
4377 captureCondition.notify_one();
4378 }
4379 });
4380
4381 result = postMessageAsync(message);
4382 if (result == NO_ERROR) {
4383 captureCondition.wait(captureLock, [&]() { return captureResult; });
4384 while (*captureResult == EAGAIN) {
4385 captureResult.reset();
4386 result = postMessageAsync(message);
4387 if (result != NO_ERROR) {
4388 return result;
4389 }
4390 captureCondition.wait(captureLock, [&]() { return captureResult; });
4391 }
4392 result = *captureResult;
4393 }
4394
4395 if (result == NO_ERROR) {
4396 // queueBuffer takes ownership of syncFd
4397 result = window->queueBuffer(window, buffer, syncFd);
4398 }
4399
4400 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004401}
4402
Mathias Agopian180f10d2013-04-10 22:55:41 -07004403
4404void SurfaceFlinger::renderScreenImplLocked(
4405 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004406 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004407 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004408 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004409{
4410 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004411 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004412
4413 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004414 const int32_t hw_w = hw->getWidth();
4415 const int32_t hw_h = hw->getHeight();
4416 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004417 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004418
Dan Stozac1879002014-05-22 15:59:05 -07004419 // if a default or invalid sourceCrop is passed in, set reasonable values
4420 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4421 !sourceCrop.isValid()) {
4422 sourceCrop.setLeftTop(Point(0, 0));
4423 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4424 }
4425
4426 // ensure that sourceCrop is inside screen
4427 if (sourceCrop.left < 0) {
4428 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4429 }
Dan Stozabe31f442014-06-11 11:20:54 -07004430 if (sourceCrop.right > hw_w) {
4431 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004432 }
4433 if (sourceCrop.top < 0) {
4434 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4435 }
Dan Stozabe31f442014-06-11 11:20:54 -07004436 if (sourceCrop.bottom > hw_h) {
4437 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004438 }
4439
Romain Guy88d37dd2017-05-26 17:57:05 -07004440#ifdef USE_HWC2
4441 engine.setWideColor(hw->getWideColorSupport());
4442 engine.setColorMode(hw->getActiveColorMode());
4443#endif
4444
Mathias Agopian180f10d2013-04-10 22:55:41 -07004445 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004446 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004447
4448 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004449 engine.setViewportAndProjection(
4450 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004451 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004452
4453 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004454 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004455
Robert Carr1f0a16a2016-10-24 16:27:39 -07004456 // We loop through the first level of layers without traversing,
4457 // as we need to interpret min/max layer Z in the top level Z space.
4458 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004459 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004460 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004461 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004462 const Layer::State& state(layer->getDrawingState());
4463 if (state.z < minLayerZ || state.z > maxLayerZ) {
4464 continue;
4465 }
Dan Stoza412903f2017-04-27 13:42:17 -07004466 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004467 if (!layer->isVisible()) {
4468 return;
4469 }
4470 if (filtering) layer->setFiltering(true);
4471 layer->draw(hw, useIdentityTransform);
4472 if (filtering) layer->setFiltering(false);
4473 });
4474 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004475
Mathias Agopian931bda12013-08-28 18:11:46 -07004476 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004477}
4478
Dan Stozaabcda352017-06-01 14:37:39 -07004479// A simple RAII class that holds an EGLImage and destroys it either:
4480// a) When the destroy() method is called
4481// b) When the object goes out of scope
4482class ImageHolder {
4483public:
4484 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4485 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004486
Dan Stozaabcda352017-06-01 14:37:39 -07004487 void destroy() {
4488 if (mImage != EGL_NO_IMAGE_KHR) {
4489 eglDestroyImageKHR(mDisplay, mImage);
4490 mImage = EGL_NO_IMAGE_KHR;
4491 }
4492 }
4493
4494private:
4495 const EGLDisplay mDisplay;
4496 EGLImageKHR mImage;
4497};
4498
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004499status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4500 ANativeWindowBuffer* buffer, Rect sourceCrop,
4501 uint32_t reqWidth, uint32_t reqHeight,
4502 int32_t minLayerZ, int32_t maxLayerZ,
4503 bool useIdentityTransform,
4504 Transform::orientation_flags rotation,
4505 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004506 ATRACE_CALL();
4507
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004508 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004509 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004510 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004511 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004512 (state.z < minLayerZ || state.z > maxLayerZ)) {
4513 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004514 }
Dan Stoza412903f2017-04-27 13:42:17 -07004515 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004516 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4517 layer->isSecure());
4518 });
4519 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004520
4521 if (!isLocalScreenshot && secureLayerIsVisible) {
4522 ALOGW("FB is protected: PERMISSION_DENIED");
4523 return PERMISSION_DENIED;
4524 }
4525
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004526 int syncFd = -1;
4527 // create an EGLImage from the buffer so we can later
4528 // turn it into a texture
4529 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4530 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4531 if (image == EGL_NO_IMAGE_KHR) {
4532 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004533 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004534
Dan Stozaabcda352017-06-01 14:37:39 -07004535 // This will automatically destroy the image if we return before calling its destroy method
4536 ImageHolder imageHolder(mEGLDisplay, image);
4537
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004538 // this binds the given EGLImage as a framebuffer for the
4539 // duration of this scope.
4540 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004541 if (imageBond.getStatus() != NO_ERROR) {
4542 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004543 return INVALID_OPERATION;
4544 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004545
Dan Stozaabcda352017-06-01 14:37:39 -07004546 // this will in fact render into our dequeued buffer
4547 // via an FBO, which means we didn't have to create
4548 // an EGLSurface and therefore we're not
4549 // dependent on the context's EGLConfig.
4550 renderScreenImplLocked(
4551 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4552 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004553
Dan Stozaabcda352017-06-01 14:37:39 -07004554 // Attempt to create a sync khr object that can produce a sync point. If that
4555 // isn't available, create a non-dupable sync object in the fallback path and
4556 // wait on it directly.
4557 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4558 if (!DEBUG_SCREENSHOTS) {
4559 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4560 // native fence fd will not be populated until flush() is done.
4561 getRenderEngine().flush();
4562 }
4563
4564 if (sync != EGL_NO_SYNC_KHR) {
4565 // get the sync fd
4566 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4567 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4568 ALOGW("captureScreen: failed to dup sync khr object");
4569 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004570 }
Dan Stozaabcda352017-06-01 14:37:39 -07004571 eglDestroySyncKHR(mEGLDisplay, sync);
4572 } else {
4573 // fallback path
4574 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004575 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004576 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4577 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4578 EGLint eglErr = eglGetError();
4579 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4580 ALOGW("captureScreen: fence wait timed out");
4581 } else {
4582 ALOGW_IF(eglErr != EGL_SUCCESS,
4583 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004584 }
4585 eglDestroySyncKHR(mEGLDisplay, sync);
4586 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004587 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004588 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004589 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004590 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004591
4592 if (DEBUG_SCREENSHOTS) {
4593 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4594 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4595 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4596 hw, minLayerZ, maxLayerZ);
4597 delete [] pixels;
4598 }
4599
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004600 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004601 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004602
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004603 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004604}
4605
Mathias Agopiand5556842013-09-19 17:08:37 -07004606void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004607 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004608 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004609 for (size_t y=0 ; y<h ; y++) {
4610 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4611 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004612 if (p[x] != 0xFF000000) return;
4613 }
4614 }
4615 ALOGE("*** we just took a black screenshot ***\n"
4616 "requested minz=%d, maxz=%d, layerStack=%d",
4617 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004618
Robert Carr2047fae2016-11-28 14:09:09 -08004619 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004620 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004621 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004622 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004623 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004624 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004625 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4626 layer->isVisible() ? '+' : '-',
4627 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004628 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004629 i++;
4630 });
4631 }
4632 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004633 }
4634}
4635
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004636// ---------------------------------------------------------------------------
4637
Dan Stoza412903f2017-04-27 13:42:17 -07004638void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4639 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004640}
4641
Dan Stoza412903f2017-04-27 13:42:17 -07004642void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4643 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004644}
4645
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004646}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004647
4648
4649#if defined(__gl_h_)
4650#error "don't include gl/gl.h in this file"
4651#endif
4652
4653#if defined(__gl2_h_)
4654#error "don't include gl2/gl2.h in this file"
4655#endif