blob: f348fb9a80db199f5705211941d89ce0775ccb22 [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);
Lloyd Pique3e3d28c2017-12-14 17:11:26 -0800630 // Process any initial hotplug and resulting display changes.
631 processDisplayHotplugEventsLocked();
632 LOG_ALWAYS_FATAL_IF(!mHwc->isConnected(HWC_DISPLAY_PRIMARY),
633 "Registered composer callback but didn't create the default primary "
634 "display");
Jesse Hall692c7232012-11-08 15:41:56 -0800635
Steven Thomas050b2c82017-03-06 11:45:16 -0800636 if (useVrFlinger) {
637 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700638 // This callback is called from the vr flinger dispatch thread. We
639 // need to call signalTransaction(), which requires holding
640 // mStateLock when we're not on the main thread. Acquiring
641 // mStateLock from the vr flinger dispatch thread might trigger a
642 // deadlock in surface flinger (see b/66916578), so post a message
643 // to be handled on the main thread instead.
644 sp<LambdaMessage> message = new LambdaMessage([=]() {
645 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
646 mVrFlingerRequestsDisplay = requestDisplay;
647 signalTransaction();
648 });
649 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800650 };
651 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
652 vrFlingerRequestDisplayCallback);
653 if (!mVrFlinger) {
654 ALOGE("Failed to start vrflinger");
655 }
656 }
657
Jamie Gennisd1700752013-10-14 12:22:52 -0700658 mEventControlThread = new EventControlThread(this);
659 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
660
Mathias Agopian92a979a2012-08-02 18:32:23 -0700661 // initialize our drawing state
662 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700663
Andy McFadden13a082e2012-08-24 10:16:42 -0700664 // set initial conditions (e.g. unblank default device)
665 initializeDisplays();
666
Dan Stoza4e637772016-07-28 13:31:51 -0700667 mRenderEngine->primeCache();
668
Wei Wangf9b05ee2017-07-19 20:59:39 -0700669 // Inform native graphics APIs whether the present timestamp is supported:
670 if (getHwComposer().hasCapability(
671 HWC2::Capability::PresentFenceIsNotReliable)) {
672 mStartPropertySetThread = new StartPropertySetThread(false);
673 } else {
674 mStartPropertySetThread = new StartPropertySetThread(true);
675 }
676
677 if (mStartPropertySetThread->Start() != NO_ERROR) {
678 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800679 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800680
Dan Stoza9e56aa02015-11-02 13:00:03 -0800681 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700682}
683
Romain Guy11d63f42017-07-20 12:47:14 -0700684void SurfaceFlinger::readPersistentProperties() {
685 char value[PROPERTY_VALUE_MAX];
686
687 property_get("persist.sys.sf.color_saturation", value, "1.0");
688 mSaturation = atof(value);
689 ALOGV("Saturation is set to %.2f", mSaturation);
690}
691
Mathias Agopiana67e4182012-06-19 17:26:12 -0700692void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800693 // Start boot animation service by setting a property mailbox
694 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700695 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800696 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700697 if (mStartPropertySetThread->join() != NO_ERROR) {
698 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800699 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700700}
701
Mathias Agopian875d8e12013-06-07 15:35:48 -0700702size_t SurfaceFlinger::getMaxTextureSize() const {
703 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700704}
705
Mathias Agopian875d8e12013-06-07 15:35:48 -0700706size_t SurfaceFlinger::getMaxViewportDims() const {
707 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700708}
709
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800710// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800711
Jamie Gennis582270d2011-08-17 18:19:00 -0700712bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800713 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800714 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800715 return authenticateSurfaceTextureLocked(bufferProducer);
716}
717
718bool SurfaceFlinger::authenticateSurfaceTextureLocked(
719 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800720 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700721 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800722}
723
Brian Anderson6b376712017-04-04 10:51:39 -0700724status_t SurfaceFlinger::getSupportedFrameTimestamps(
725 std::vector<FrameEvent>* outSupported) const {
726 *outSupported = {
727 FrameEvent::REQUESTED_PRESENT,
728 FrameEvent::ACQUIRE,
729 FrameEvent::LATCH,
730 FrameEvent::FIRST_REFRESH_START,
731 FrameEvent::LAST_REFRESH_START,
732 FrameEvent::GPU_COMPOSITION_DONE,
733 FrameEvent::DEQUEUE_READY,
734 FrameEvent::RELEASE,
735 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700736 ConditionalLock _l(mStateLock,
737 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700738 if (!getHwComposer().hasCapability(
739 HWC2::Capability::PresentFenceIsNotReliable)) {
740 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
741 }
742 return NO_ERROR;
743}
744
Dan Stoza7f7da322014-05-02 15:26:25 -0700745status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
746 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700747 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700748 return BAD_VALUE;
749 }
750
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500751 if (!display.get())
752 return NAME_NOT_FOUND;
753
Jesse Hall692c7232012-11-08 15:41:56 -0800754 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700755 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800756 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700757 type = i;
758 break;
759 }
760 }
761
762 if (type < 0) {
763 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700764 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700765
Mathias Agopian8b736f12012-08-13 17:54:26 -0700766 // TODO: Not sure if display density should handled by SF any longer
767 class Density {
768 static int getDensityFromProperty(char const* propName) {
769 char property[PROPERTY_VALUE_MAX];
770 int density = 0;
771 if (property_get(propName, property, NULL) > 0) {
772 density = atoi(property);
773 }
774 return density;
775 }
776 public:
777 static int getEmuDensity() {
778 return getDensityFromProperty("qemu.sf.lcd_density"); }
779 static int getBuildDensity() {
780 return getDensityFromProperty("ro.sf.lcd_density"); }
781 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700782
Dan Stoza7f7da322014-05-02 15:26:25 -0700783 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700784
Steven Thomas6d8110b2017-08-31 18:24:21 -0700785 ConditionalLock _l(mStateLock,
786 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800787 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700788 DisplayInfo info = DisplayInfo();
789
Dan Stoza9e56aa02015-11-02 13:00:03 -0800790 float xdpi = hwConfig->getDpiX();
791 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700792
793 if (type == DisplayDevice::DISPLAY_PRIMARY) {
794 // The density of the device is provided by a build property
795 float density = Density::getBuildDensity() / 160.0f;
796 if (density == 0) {
797 // the build doesn't provide a density -- this is wrong!
798 // use xdpi instead
799 ALOGE("ro.sf.lcd_density must be defined as a build property");
800 density = xdpi / 160.0f;
801 }
802 if (Density::getEmuDensity()) {
803 // if "qemu.sf.lcd_density" is specified, it overrides everything
804 xdpi = ydpi = density = Density::getEmuDensity();
805 density /= 160.0f;
806 }
807 info.density = density;
808
809 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700810 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000811 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700812 } else {
813 // TODO: where should this value come from?
814 static const int TV_DENSITY = 213;
815 info.density = TV_DENSITY / 160.0f;
816 info.orientation = 0;
817 }
818
Dan Stoza9e56aa02015-11-02 13:00:03 -0800819 info.w = hwConfig->getWidth();
820 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700821 info.xdpi = xdpi;
822 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800823 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900824 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800825
Andy McFadden91b2ca82014-06-13 14:04:23 -0700826 // This is how far in advance a buffer must be queued for
827 // presentation at a given time. If you want a buffer to appear
828 // on the screen at time N, you must submit the buffer before
829 // (N - presentationDeadline).
830 //
831 // Normally it's one full refresh period (to give SF a chance to
832 // latch the buffer), but this can be reduced by configuring a
833 // DispSync offset. Any additional delays introduced by the hardware
834 // composer or panel must be accounted for here.
835 //
836 // We add an additional 1ms to allow for processing time and
837 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800839 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700840
841 // All non-virtual displays are currently considered secure.
842 info.secure = true;
843
Michael Wright28f24d02016-07-12 13:30:53 -0700844 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700845 }
846
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 return NO_ERROR;
848}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700849
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800850status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700851 DisplayStatInfo* stats) {
852 if (stats == NULL) {
853 return BAD_VALUE;
854 }
855
856 // FIXME for now we always return stats for the primary display
857 memset(stats, 0, sizeof(*stats));
858 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
859 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
860 return NO_ERROR;
861}
862
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700863int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800864 if (display == NULL) {
865 ALOGE("%s : display is NULL", __func__);
866 return BAD_VALUE;
867 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700868
869 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700870 if (device != NULL) {
871 return device->getActiveConfig();
872 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700873
Dan Stoza24a42e92015-03-09 10:04:11 -0700874 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700875}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700876
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700877void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
878 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
879 this);
880 int32_t type = hw->getDisplayType();
881 int currentMode = hw->getActiveConfig();
882
883 if (mode == currentMode) {
884 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
885 return;
886 }
887
888 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
889 ALOGW("Trying to set config for virtual display");
890 return;
891 }
892
893 hw->setActiveConfig(mode);
894 getHwComposer().setActiveConfig(type, mode);
895}
896
897status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
898 class MessageSetActiveConfig: public MessageBase {
899 SurfaceFlinger& mFlinger;
900 sp<IBinder> mDisplay;
901 int mMode;
902 public:
903 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
904 int mode) :
905 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
906 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700907 Vector<DisplayInfo> configs;
908 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700909 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700910 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700911 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700912 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700913 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700914 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
915 if (hw == NULL) {
916 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700917 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700918 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
919 ALOGW("Attempt to set active config = %d for virtual display",
920 mMode);
921 } else {
922 mFlinger.setActiveConfigInternal(hw, mMode);
923 }
924 return true;
925 }
926 };
927 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
928 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700929 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700930}
Michael Wright28f24d02016-07-12 13:30:53 -0700931status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
932 Vector<android_color_mode_t>* outColorModes) {
933 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
934 return BAD_VALUE;
935 }
936
937 if (!display.get()) {
938 return NAME_NOT_FOUND;
939 }
940
941 int32_t type = NAME_NOT_FOUND;
942 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
943 if (display == mBuiltinDisplays[i]) {
944 type = i;
945 break;
946 }
947 }
948
949 if (type < 0) {
950 return type;
951 }
952
Steven Thomas6d8110b2017-08-31 18:24:21 -0700953 std::vector<android_color_mode_t> modes;
954 {
955 ConditionalLock _l(mStateLock,
956 std::this_thread::get_id() != mMainThreadId);
957 modes = getHwComposer().getColorModes(type);
958 }
Michael Wright28f24d02016-07-12 13:30:53 -0700959 outColorModes->clear();
960 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
961
962 return NO_ERROR;
963}
964
965android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700966 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700967 if (device != nullptr) {
968 return device->getActiveColorMode();
969 }
970 return static_cast<android_color_mode_t>(BAD_VALUE);
971}
972
973void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
974 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700975 int32_t type = hw->getDisplayType();
976 android_color_mode_t currentMode = hw->getActiveColorMode();
977
978 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700979 return;
980 }
981
982 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
983 ALOGW("Trying to set config for virtual display");
984 return;
985 }
986
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600987 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
988 hw->getDisplayType());
989
Michael Wright28f24d02016-07-12 13:30:53 -0700990 hw->setActiveColorMode(mode);
991 getHwComposer().setActiveColorMode(type, mode);
992}
993
994
995status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
996 android_color_mode_t colorMode) {
997 class MessageSetActiveColorMode: public MessageBase {
998 SurfaceFlinger& mFlinger;
999 sp<IBinder> mDisplay;
1000 android_color_mode_t mMode;
1001 public:
1002 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1003 android_color_mode_t mode) :
1004 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1005 virtual bool handler() {
1006 Vector<android_color_mode_t> modes;
1007 mFlinger.getDisplayColorModes(mDisplay, &modes);
1008 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1009 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001010 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1011 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001012 return true;
1013 }
1014 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1015 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001016 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1017 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001018 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001019 ALOGW("Attempt to set active color mode %s %d for virtual display",
1020 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001021 } else {
1022 mFlinger.setActiveColorModeInternal(hw, mMode);
1023 }
1024 return true;
1025 }
1026 };
1027 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1028 postMessageSync(msg);
1029 return NO_ERROR;
1030}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001031
Svetoslavd85084b2014-03-20 10:28:31 -07001032status_t SurfaceFlinger::clearAnimationFrameStats() {
1033 Mutex::Autolock _l(mStateLock);
1034 mAnimFrameTracker.clearStats();
1035 return NO_ERROR;
1036}
1037
1038status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1039 Mutex::Autolock _l(mStateLock);
1040 mAnimFrameTracker.getStats(outStats);
1041 return NO_ERROR;
1042}
1043
Dan Stozac4f471e2016-03-24 09:31:08 -07001044status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1045 HdrCapabilities* outCapabilities) const {
1046 Mutex::Autolock _l(mStateLock);
1047
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001048 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001049 if (displayDevice == nullptr) {
1050 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1051 return BAD_VALUE;
1052 }
1053
1054 std::unique_ptr<HdrCapabilities> capabilities =
1055 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1056 if (capabilities) {
1057 std::swap(*outCapabilities, *capabilities);
1058 } else {
1059 return BAD_VALUE;
1060 }
1061
1062 return NO_ERROR;
1063}
1064
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001065status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1066 if (enable == mInjectVSyncs) {
1067 return NO_ERROR;
1068 }
1069
1070 if (enable) {
1071 mInjectVSyncs = enable;
1072 ALOGV("VSync Injections enabled");
1073 if (mVSyncInjector.get() == nullptr) {
1074 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001075 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001076 }
1077 mEventQueue.setEventThread(mInjectorEventThread);
1078 } else {
1079 mInjectVSyncs = enable;
1080 ALOGV("VSync Injections disabled");
1081 mEventQueue.setEventThread(mSFEventThread);
1082 mVSyncInjector.clear();
1083 }
1084 return NO_ERROR;
1085}
1086
1087status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1088 if (!mInjectVSyncs) {
1089 ALOGE("VSync Injections not enabled");
1090 return BAD_VALUE;
1091 }
1092 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1093 ALOGV("Injecting VSync inside SurfaceFlinger");
1094 mVSyncInjector->onInjectSyncEvent(when);
1095 }
1096 return NO_ERROR;
1097}
1098
Kalle Raitaa099a242017-01-11 11:17:29 -08001099status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1100 IPCThreadState* ipc = IPCThreadState::self();
1101 const int pid = ipc->getCallingPid();
1102 const int uid = ipc->getCallingUid();
1103 if ((uid != AID_SHELL) &&
1104 !PermissionCache::checkPermission(sDump, pid, uid)) {
1105 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1106 return PERMISSION_DENIED;
1107 }
1108
1109 // Try to acquire a lock for 1s, fail gracefully
1110 const status_t err = mStateLock.timedLock(s2ns(1));
1111 const bool locked = (err == NO_ERROR);
1112 if (!locked) {
1113 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1114 return TIMED_OUT;
1115 }
1116
1117 outLayers->clear();
1118 mCurrentState.traverseInZOrder([&](Layer* layer) {
1119 outLayers->push_back(layer->getLayerDebugInfo());
1120 });
1121
1122 mStateLock.unlock();
1123 return NO_ERROR;
1124}
1125
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001126// ----------------------------------------------------------------------------
1127
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001128sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1129 ISurfaceComposer::VsyncSource vsyncSource) {
1130 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1131 return mSFEventThread->createEventConnection();
1132 } else {
1133 return mEventThread->createEventConnection();
1134 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001135}
1136
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001137// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001138
1139void SurfaceFlinger::waitForEvent() {
1140 mEventQueue.waitMessage();
1141}
1142
1143void SurfaceFlinger::signalTransaction() {
1144 mEventQueue.invalidate();
1145}
1146
1147void SurfaceFlinger::signalLayerUpdate() {
1148 mEventQueue.invalidate();
1149}
1150
1151void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001152 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001153 mEventQueue.refresh();
1154}
1155
1156status_t SurfaceFlinger::postMessageAsync(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 return mEventQueue.postMessage(msg, reltime);
1159}
1160
1161status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001162 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001163 status_t res = mEventQueue.postMessage(msg, reltime);
1164 if (res == NO_ERROR) {
1165 msg->wait();
1166 }
1167 return res;
1168}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001169
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001170void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001171 do {
1172 waitForEvent();
1173 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001174}
1175
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001176void SurfaceFlinger::enableHardwareVsync() {
1177 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001178 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001179 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001180 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1181 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001182 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001183 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184}
1185
Jesse Hall948fe0c2013-10-14 12:56:09 -07001186void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187 Mutex::Autolock _l(mHWVsyncLock);
1188
Jesse Hall948fe0c2013-10-14 12:56:09 -07001189 if (makeAvailable) {
1190 mHWVsyncAvailable = true;
1191 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001192 // Hardware vsync is not currently available, so abort the resync
1193 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001194 return;
1195 }
1196
Dan Stoza9e56aa02015-11-02 13:00:03 -08001197 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1198 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001199
1200 mPrimaryDispSync.reset();
1201 mPrimaryDispSync.setPeriod(period);
1202
1203 if (!mPrimaryHWVsyncEnabled) {
1204 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001205 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1206 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001207 mPrimaryHWVsyncEnabled = true;
1208 }
1209}
1210
Jesse Hall948fe0c2013-10-14 12:56:09 -07001211void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001212 Mutex::Autolock _l(mHWVsyncLock);
1213 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001214 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1215 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001216 mPrimaryDispSync.endResync();
1217 mPrimaryHWVsyncEnabled = false;
1218 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001219 if (makeUnavailable) {
1220 mHWVsyncAvailable = false;
1221 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001222}
1223
Tim Murray4a4e4a22016-04-19 16:29:23 +00001224void SurfaceFlinger::resyncWithRateLimit() {
1225 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001226
1227 // No explicit locking is needed here since EventThread holds a lock while calling this method
1228 static nsecs_t sLastResyncAttempted = 0;
1229 const nsecs_t now = systemTime();
1230 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001231 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001232 }
Dan Stoza57164302017-05-08 14:03:54 -07001233 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001234}
1235
Steven Thomasb02664d2017-07-26 18:48:28 -07001236void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1237 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001238 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001239 // Ignore any vsyncs from a previous hardware composer.
1240 if (sequenceId != mComposerSequenceId) {
1241 return;
1242 }
1243
1244 int32_t type;
1245 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001246 return;
1247 }
1248
Jamie Gennisd1700752013-10-14 12:22:52 -07001249 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001250
Jamie Gennisd1700752013-10-14 12:22:52 -07001251 { // Scope for the lock
1252 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001253 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001254 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001256 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001257
1258 if (needsHwVsync) {
1259 enableHardwareVsync();
1260 } else {
1261 disableHardwareVsync(false);
1262 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001263}
1264
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001265void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001266 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001267 *compositorTiming = mCompositorTiming;
1268}
1269
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001270void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001271 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001272 wp<IBinder> token = mBuiltinDisplays[type];
1273
1274 // All non-virtual displays are currently considered secure.
1275 const bool isSecure = true;
1276
1277 sp<IGraphicBufferProducer> producer;
1278 sp<IGraphicBufferConsumer> consumer;
1279 BufferQueue::createBufferQueue(&producer, &consumer);
1280
1281 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1282
1283 bool hasWideColorModes = false;
1284 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1285 for (android_color_mode_t colorMode : modes) {
1286 switch (colorMode) {
1287 case HAL_COLOR_MODE_DISPLAY_P3:
1288 case HAL_COLOR_MODE_ADOBE_RGB:
1289 case HAL_COLOR_MODE_DCI_P3:
1290 hasWideColorModes = true;
1291 break;
1292 default:
1293 break;
1294 }
1295 }
1296 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1297 token, fbs, producer, mRenderEngine->getEGLConfig(),
1298 hasWideColorModes && hasWideColorDisplay);
1299 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001300 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1301 if (hasWideColorModes && hasWideColorDisplay) {
1302 defaultColorMode = HAL_COLOR_MODE_SRGB;
1303 }
1304 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001305 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001306
1307 // Add the primary display token to mDrawingState so we don't try to
1308 // recreate the DisplayDevice for the primary display.
1309 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1310
1311 // make the GLContext current so that we can create textures when creating
1312 // Layers (which may happens before we render something)
1313 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001314}
1315
Steven Thomasb02664d2017-07-26 18:48:28 -07001316void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1317 hwc2_display_t display, HWC2::Connection connection,
1318 bool primaryDisplay) {
1319 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1320 sequenceId, display,
1321 connection == HWC2::Connection::Connected ?
1322 "connected" : "disconnected",
1323 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001324
Lloyd Pique3e3d28c2017-12-14 17:11:26 -08001325 // Ignore events that do not have the right sequenceId.
1326 if (sequenceId != mComposerSequenceId) {
1327 return;
1328 }
1329
Steven Thomasb02664d2017-07-26 18:48:28 -07001330 // Only lock if we're not on the main thread. This function is normally
1331 // called on a hwbinder thread, but for the primary display it's called on
1332 // the main thread with the state lock already held, so don't attempt to
1333 // acquire it here.
Lloyd Pique3e3d28c2017-12-14 17:11:26 -08001334 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001335
Lloyd Pique3e3d28c2017-12-14 17:11:26 -08001336 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection, primaryDisplay});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001337
Lloyd Pique3e3d28c2017-12-14 17:11:26 -08001338 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001339}
1340
Steven Thomasb02664d2017-07-26 18:48:28 -07001341void SurfaceFlinger::onRefreshReceived(int sequenceId,
1342 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001343 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 if (sequenceId != mComposerSequenceId) {
1345 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001346 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001347 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001348}
1349
Dan Stoza9e56aa02015-11-02 13:00:03 -08001350void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001351 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001352 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001353 getHwComposer().setVsyncEnabled(disp,
1354 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001355}
1356
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001357// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001358void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001359 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001360 // Clear the drawing state so that the logic inside of
1361 // handleTransactionLocked will fire. It will determine the delta between
1362 // mCurrentState and mDrawingState and re-apply all changes when we make the
1363 // transition.
1364 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001365 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001366 mDisplays.clear();
1367}
1368
Steven Thomas050b2c82017-03-06 11:45:16 -08001369void SurfaceFlinger::updateVrFlinger() {
1370 if (!mVrFlinger)
1371 return;
1372 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1373 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001374 return;
1375 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001376
Steven Thomasb02664d2017-07-26 18:48:28 -07001377 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1378 ALOGE("Vr flinger is only supported for remote hardware composer"
1379 " service connections. Ignoring request to transition to vr"
1380 " flinger.");
1381 mVrFlingerRequestsDisplay = false;
1382 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001383 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001384
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001385 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001386
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 int currentDisplayPowerMode = getDisplayDeviceLocked(
1388 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001391 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001392 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001393
Steven Thomasb02664d2017-07-26 18:48:28 -07001394 resetDisplayState();
1395 mHwc.reset(); // Delete the current instance before creating the new one
1396 mHwc.reset(new HWComposer(
1397 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1398 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1401 "Switched to non-remote hardware composer");
1402
1403 if (vrFlingerRequestsDisplay) {
1404 mVrFlinger->GrantDisplayOwnership();
1405 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408
1409 mVisibleRegionsDirty = true;
1410 invalidateHwcGeometry();
1411
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001412 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1414 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1415 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001416
Steven Thomasb02664d2017-07-26 18:48:28 -07001417 // Reset the timing values to account for the period of the swapped in HWC
1418 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1419 const nsecs_t period = activeConfig->getVsyncPeriod();
1420 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001421
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 // Use phase of 0 since phase is not known.
1423 // Use latency of 0, which will snap to the ideal latency.
1424 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001425
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426 android_atomic_or(1, &mRepaintEverything);
1427 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001428}
1429
Mathias Agopian4fec8732012-06-29 14:12:52 -07001430void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001431 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001432 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001433 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001434 bool frameMissed = !mHadClientComposition &&
1435 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001436 (mPreviousPresentFence->getSignalTime() ==
1437 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001438 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001439 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001440 signalLayerUpdate();
1441 break;
1442 }
1443
Steven Thomas050b2c82017-03-06 11:45:16 -08001444 // Now that we're going to make it to the handleMessageTransaction()
1445 // call below it's safe to call updateVrFlinger(), which will
1446 // potentially trigger a display handoff.
1447 updateVrFlinger();
1448
Dan Stoza6b9454d2014-11-07 16:00:59 -08001449 bool refreshNeeded = handleMessageTransaction();
1450 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001451 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001452 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001453 // Signal a refresh if a transaction modified the window state,
1454 // a new buffer was latched, or if HWC has requested a full
1455 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001456 signalRefresh();
1457 }
1458 break;
1459 }
1460 case MessageQueue::REFRESH: {
1461 handleMessageRefresh();
1462 break;
1463 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001464 }
1465}
1466
Dan Stoza6b9454d2014-11-07 16:00:59 -08001467bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001468 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001469 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001470 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001471 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001472 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001473 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001474}
1475
Dan Stoza6b9454d2014-11-07 16:00:59 -08001476bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001477 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001479}
1480
1481void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001482 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001483
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001484 mRefreshPending = false;
1485
Pablo Ceballos40845df2016-01-25 17:41:15 -08001486 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001487
Brian Andersond6927fb2016-07-23 23:37:30 -07001488 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001489 rebuildLayerStacks();
1490 setUpHWComposer();
1491 doDebugFlashRegions();
1492 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001493 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001494
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001495 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001496
1497 mHadClientComposition = false;
1498 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1499 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1500 mHadClientComposition = mHadClientComposition ||
1501 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1502 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001503
Dan Stoza9e56aa02015-11-02 13:00:03 -08001504 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001505}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001506
Mathias Agopiancd60f992012-08-16 16:28:27 -07001507void SurfaceFlinger::doDebugFlashRegions()
1508{
1509 // is debugging enabled
1510 if (CC_LIKELY(!mDebugRegion))
1511 return;
1512
1513 const bool repaintEverything = mRepaintEverything;
1514 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1515 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001516 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001517 // transform the dirty region into this screen's coordinate space
1518 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1519 if (!dirtyRegion.isEmpty()) {
1520 // redraw the whole screen
1521 doComposeSurfaces(hw, Region(hw->bounds()));
1522
1523 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001525 RenderEngine& engine(getRenderEngine());
1526 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1527
Mathias Agopianda27af92012-09-13 18:17:13 -07001528 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001529 }
1530 }
1531 }
1532
1533 postFramebuffer();
1534
1535 if (mDebugRegion > 1) {
1536 usleep(mDebugRegion * 1000);
1537 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001538
Dan Stoza9e56aa02015-11-02 13:00:03 -08001539 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001540 auto& displayDevice = mDisplays[displayId];
1541 if (!displayDevice->isDisplayOn()) {
1542 continue;
1543 }
1544
1545 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001546 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1547 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001548 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001549}
1550
Brian Andersond6927fb2016-07-23 23:37:30 -07001551void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001552{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001553 ATRACE_CALL();
1554 ALOGV("preComposition");
1555
Mathias Agopiancd60f992012-08-16 16:28:27 -07001556 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001557 mDrawingState.traverseInZOrder([&](Layer* layer) {
1558 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559 needExtraInvalidate = true;
1560 }
Robert Carr2047fae2016-11-28 14:09:09 -08001561 });
1562
Mathias Agopiancd60f992012-08-16 16:28:27 -07001563 if (needExtraInvalidate) {
1564 signalLayerUpdate();
1565 }
1566}
1567
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001568void SurfaceFlinger::updateCompositorTiming(
1569 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1570 std::shared_ptr<FenceTime>& presentFenceTime) {
1571 // Update queue of past composite+present times and determine the
1572 // most recently known composite to present latency.
1573 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1574 nsecs_t compositeToPresentLatency = -1;
1575 while (!mCompositePresentTimes.empty()) {
1576 CompositePresentTime& cpt = mCompositePresentTimes.front();
1577 // Cached values should have been updated before calling this method,
1578 // which helps avoid duplicate syscalls.
1579 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1580 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1581 break;
1582 }
1583 compositeToPresentLatency = displayTime - cpt.composite;
1584 mCompositePresentTimes.pop();
1585 }
1586
1587 // Don't let mCompositePresentTimes grow unbounded, just in case.
1588 while (mCompositePresentTimes.size() > 16) {
1589 mCompositePresentTimes.pop();
1590 }
1591
Brian Andersond0010582017-03-07 13:20:31 -08001592 setCompositorTimingSnapped(
1593 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1594}
1595
1596void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1597 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001598 // Integer division and modulo round toward 0 not -inf, so we need to
1599 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001600 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001601 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1602 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1603
Brian Andersond0010582017-03-07 13:20:31 -08001604 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1605 if (idealLatency <= 0) {
1606 idealLatency = vsyncInterval;
1607 }
1608
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001609 // Snap the latency to a value that removes scheduling jitter from the
1610 // composition and present times, which often have >1ms of jitter.
1611 // Reducing jitter is important if an app attempts to extrapolate
1612 // something (such as user input) to an accurate diasplay time.
1613 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1614 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001615 nsecs_t bias = vsyncInterval / 2;
1616 int64_t extraVsyncs =
1617 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1618 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1619 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001620
Brian Andersond0010582017-03-07 13:20:31 -08001621 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001622 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1623 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001624 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001625}
1626
1627void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001628{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001629 ATRACE_CALL();
1630 ALOGV("postComposition");
1631
Brian Anderson3546a3f2016-07-14 11:51:14 -07001632 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001633 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001634 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001635 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001636 }
1637
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001638 // |mStateLock| not needed as we are on the main thread
1639 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001640
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001641 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001642 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1643 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1644 glCompositionDoneFenceTime =
1645 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1646 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1647 } else {
1648 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1649 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001650
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001651 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001652 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1653 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1654 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001655
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1657 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1658
1659 // We use the refreshStartTime which might be sampled a little later than
1660 // when we started doing work for this frame, but that should be okay
1661 // since updateCompositorTiming has snapping logic.
1662 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001663 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001664 CompositorTiming compositorTiming;
1665 {
1666 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1667 compositorTiming = mCompositorTiming;
1668 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001669
Robert Carr2047fae2016-11-28 14:09:09 -08001670 mDrawingState.traverseInZOrder([&](Layer* layer) {
1671 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001672 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001673 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001674 recordBufferingStats(layer->getName().string(),
1675 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001676 }
Robert Carr2047fae2016-11-28 14:09:09 -08001677 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001678
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001679 if (presentFenceTime->isValid()) {
1680 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001681 enableHardwareVsync();
1682 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001683 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001684 }
1685 }
1686
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001687 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001688 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001689 enableHardwareVsync();
1690 }
1691 }
1692
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001693 if (mAnimCompositionPending) {
1694 mAnimCompositionPending = false;
1695
Brian Anderson4e606e32017-03-16 15:34:57 -07001696 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001697 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001698 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001699 } else {
1700 // The HWC doesn't support present fences, so use the refresh
1701 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001702 nsecs_t presentTime =
1703 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001704 mAnimFrameTracker.setActualPresentTime(presentTime);
1705 }
1706 mAnimFrameTracker.advanceFrame();
1707 }
Dan Stozab90cf072015-03-05 11:05:59 -08001708
1709 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1710 return;
1711 }
1712
1713 nsecs_t currentTime = systemTime();
1714 if (mHasPoweredOff) {
1715 mHasPoweredOff = false;
1716 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001717 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001718 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001719 if (numPeriods < NUM_BUCKETS - 1) {
1720 mFrameBuckets[numPeriods] += elapsedTime;
1721 } else {
1722 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1723 }
1724 mTotalTime += elapsedTime;
1725 }
1726 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001727}
1728
1729void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001730 ATRACE_CALL();
1731 ALOGV("rebuildLayerStacks");
1732
Mathias Agopiancd60f992012-08-16 16:28:27 -07001733 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001734 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1735 ATRACE_CALL();
1736 mVisibleRegionsDirty = false;
1737 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001738
Jeff Sharkey76488112017-02-27 14:15:18 -07001739 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1740 Region opaqueRegion;
1741 Region dirtyRegion;
1742 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001743 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001744 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1745 const Transform& tr(displayDevice->getTransform());
1746 const Rect bounds(displayDevice->getBounds());
1747 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001748 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001749
Jeff Sharkey76488112017-02-27 14:15:18 -07001750 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001751 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001752 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1753 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001754 Region drawRegion(tr.transform(
1755 layer->visibleNonTransparentRegion));
1756 drawRegion.andSelf(bounds);
1757 if (!drawRegion.isEmpty()) {
1758 layersSortedByZ.add(layer);
1759 } else {
1760 // Clear out the HWC layer if this layer was
1761 // previously visible, but no longer is
Chia-I Wu92257612017-11-20 10:43:41 -08001762 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001763 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001764 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001765 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001766 // WM changes displayDevice->layerStack upon sleep/awake.
1767 // Here we make sure we delete the HWC layers even if
1768 // WM changed their layer stack.
Chia-I Wu92257612017-11-20 10:43:41 -08001769 hwcLayerDestroyed = layer->destroyHwcLayer(
1770 displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001771 }
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001772
1773 // If a layer is not going to get a release fence because
1774 // it is invisible, but it is also going to release its
1775 // old buffer, add it to the list of layers needing
1776 // fences.
1777 if (hwcLayerDestroyed) {
1778 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1779 mLayersWithQueuedFrames.cend(), layer);
1780 if (found != mLayersWithQueuedFrames.cend()) {
1781 layersNeedingFences.add(layer);
1782 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001783 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001784 });
1785 }
1786 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001787 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001788 displayDevice->undefinedRegion.set(bounds);
1789 displayDevice->undefinedRegion.subtractSelf(
1790 tr.transform(opaqueRegion));
1791 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001792 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001793 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001794}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001795
Romain Guy0147a172017-06-01 13:53:56 -07001796mat4 SurfaceFlinger::computeSaturationMatrix() const {
1797 if (mSaturation == 1.0f) {
1798 return mat4();
1799 }
1800
1801 // Rec.709 luma coefficients
1802 float3 luminance{0.213f, 0.715f, 0.072f};
1803 luminance *= 1.0f - mSaturation;
1804 return mat4(
1805 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1806 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1807 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1808 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1809 );
1810}
1811
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001812// pickColorMode translates a given dataspace into the best available color mode.
1813// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001814android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001815 switch (dataSpace) {
1816 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1817 // system expects.
1818 case HAL_DATASPACE_UNKNOWN:
1819 case HAL_DATASPACE_SRGB:
1820 case HAL_DATASPACE_V0_SRGB:
1821 return HAL_COLOR_MODE_SRGB;
1822 break;
1823
1824 case HAL_DATASPACE_DISPLAY_P3:
1825 return HAL_COLOR_MODE_DISPLAY_P3;
1826 break;
1827
1828 default:
1829 // TODO (courtneygo): Do we want to assert an error here?
1830 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1831 dataSpace);
1832 return HAL_COLOR_MODE_SRGB;
1833 break;
1834 }
1835}
1836
Romain Guy0147a172017-06-01 13:53:56 -07001837android_dataspace SurfaceFlinger::bestTargetDataSpace(
1838 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001839 // Only support sRGB and Display-P3 right now.
1840 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1841 return HAL_DATASPACE_DISPLAY_P3;
1842 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001843 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1844 return HAL_DATASPACE_DISPLAY_P3;
1845 }
1846 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1847 return HAL_DATASPACE_DISPLAY_P3;
1848 }
1849
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001850 return HAL_DATASPACE_V0_SRGB;
1851}
1852
Mathias Agopiancd60f992012-08-16 16:28:27 -07001853void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001854 ATRACE_CALL();
1855 ALOGV("setUpHWComposer");
1856
Jesse Hall028dc8f2013-08-20 16:35:32 -07001857 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001858 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1859 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1860 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1861
1862 // If nothing has changed (!dirty), don't recompose.
1863 // If something changed, but we don't currently have any visible layers,
1864 // and didn't when we last did a composition, then skip it this time.
1865 // The second rule does two things:
1866 // - When all layers are removed from a display, we'll emit one black
1867 // frame, then nothing more until we get new layers.
1868 // - When a display is created with a private layer stack, we won't
1869 // emit any black frames until a layer is added to the layer stack.
1870 bool mustRecompose = dirty && !(empty && wasEmpty);
1871
1872 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1873 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1874 mustRecompose ? "doing" : "skipping",
1875 dirty ? "+" : "-",
1876 empty ? "+" : "-",
1877 wasEmpty ? "+" : "-");
1878
Dan Stoza71433162014-02-04 16:22:36 -08001879 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001880
1881 if (mustRecompose) {
1882 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1883 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001884 }
1885
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 // build the h/w work list
1887 if (CC_UNLIKELY(mGeometryInvalid)) {
1888 mGeometryInvalid = false;
1889 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1890 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1891 const auto hwcId = displayDevice->getHwcDisplayId();
1892 if (hwcId >= 0) {
1893 const Vector<sp<Layer>>& currentLayers(
1894 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001895 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001896 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001898 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001899 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001900 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001901 }
1902 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001903
Robert Carrae060832016-11-28 10:51:00 -08001904 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001905 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001906 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001907 }
1908 }
1909 }
1910 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001911 }
Riley Andrews03414a12014-07-01 14:22:59 -07001912
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001913
Romain Guy0147a172017-06-01 13:53:56 -07001914 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001915
Dan Stoza9e56aa02015-11-02 13:00:03 -08001916 // Set the per-frame data
1917 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1918 auto& displayDevice = mDisplays[displayId];
1919 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001920
Dan Stoza9e56aa02015-11-02 13:00:03 -08001921 if (hwcId < 0) {
1922 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001923 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001924 if (colorMatrix != mPreviousColorMatrix) {
1925 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1926 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1927 "display %zd: %d", displayId, result);
1928 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001929 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1930 layer->setPerFrameData(displayDevice);
1931 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001932
1933 if (hasWideColorDisplay) {
1934 android_color_mode newColorMode;
1935 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1936
1937 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1938 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1939 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1940 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1941 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1942 }
1943 newColorMode = pickColorMode(newDataSpace);
1944
Thierry Strudel2924d012017-08-14 15:19:37 -07001945 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001946 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001947 }
1948
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001949 mPreviousColorMatrix = colorMatrix;
1950
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001952 auto& displayDevice = mDisplays[displayId];
1953 if (!displayDevice->isDisplayOn()) {
1954 continue;
1955 }
1956
1957 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001958 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1959 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001960 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001961}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001962
Mathias Agopiancd60f992012-08-16 16:28:27 -07001963void SurfaceFlinger::doComposition() {
1964 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001965 ALOGV("doComposition");
1966
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001967 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001968 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001969 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001970 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001971 // transform the dirty region into this screen's coordinate space
1972 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001973
1974 // repaint the framebuffer (if needed)
1975 doDisplayComposition(hw, dirtyRegion);
1976
Mathias Agopiancd60f992012-08-16 16:28:27 -07001977 hw->dirtyRegion.clear();
1978 hw->flip(hw->swapRegion);
1979 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001980 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001981 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001982 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001983}
1984
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001985void SurfaceFlinger::postFramebuffer()
1986{
Mathias Agopian841cde52012-03-01 15:44:37 -08001987 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001988 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001989
Mathias Agopiana44b0412011-10-16 18:46:35 -07001990 const nsecs_t now = systemTime();
1991 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001992
Dan Stoza9e56aa02015-11-02 13:00:03 -08001993 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1994 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001995 if (!displayDevice->isDisplayOn()) {
1996 continue;
1997 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001998 const auto hwcId = displayDevice->getHwcDisplayId();
1999 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002000 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002001 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002002 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002003 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002005 // The layer buffer from the previous frame (if any) is released
2006 // by HWC only when the release fence from this frame (if any) is
2007 // signaled. Always get the release fence from HWC first.
2008 auto hwcLayer = layer->getHwcLayer(hwcId);
2009 sp<Fence> releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2010
2011 // If the layer was client composited in the previous frame, we
2012 // need to merge with the previous client target acquire fence.
2013 // Since we do not track that, always merge with the current
2014 // client target acquire fence when it is available, even though
2015 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002016 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002017 releaseFence = Fence::merge("LayerRelease", releaseFence,
2018 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002019 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002020
Dan Stoza9e56aa02015-11-02 13:00:03 -08002021 layer->onLayerDisplayed(releaseFence);
2022 }
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08002023
2024 // We've got a list of layers needing fences, that are disjoint with
2025 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2026 // supply them with the present fence.
2027 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
2028 sp<Fence> presentFence = mHwc->getPresentFence(hwcId);
2029 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2030 layer->onLayerDisplayed(presentFence);
2031 }
2032 }
2033
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 if (hwcId >= 0) {
2035 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002036 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002037 }
2038
Mathias Agopiana44b0412011-10-16 18:46:35 -07002039 mLastSwapBufferTime = systemTime() - now;
2040 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002041
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002042 // |mStateLock| not needed as we are on the main thread
2043 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002044 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2045 logFrameStats();
2046 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002047}
2048
Mathias Agopian87baae12012-07-31 12:38:26 -07002049void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002050{
Mathias Agopian841cde52012-03-01 15:44:37 -08002051 ATRACE_CALL();
2052
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002053 // here we keep a copy of the drawing state (that is the state that's
2054 // going to be overwritten by handleTransactionLocked()) outside of
2055 // mStateLock so that the side-effects of the State assignment
2056 // don't happen with mStateLock held (which can cause deadlocks).
2057 State drawingState(mDrawingState);
2058
Mathias Agopianca4d3602011-05-19 15:38:14 -07002059 Mutex::Autolock _l(mStateLock);
2060 const nsecs_t now = systemTime();
2061 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002062
Mathias Agopianca4d3602011-05-19 15:38:14 -07002063 // Here we're guaranteed that some transaction flags are set
2064 // so we can call handleTransactionLocked() unconditionally.
2065 // We call getTransactionFlags(), which will also clear the flags,
2066 // with mStateLock held to guarantee that mCurrentState won't change
2067 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002068
Mathias Agopiane57f2922012-08-09 16:29:12 -07002069 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002070 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002071
Mathias Agopianca4d3602011-05-19 15:38:14 -07002072 mLastTransactionTime = systemTime() - now;
2073 mDebugInTransaction = 0;
2074 invalidateHwcGeometry();
2075 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002076}
2077
Lloyd Pique3e3d28c2017-12-14 17:11:26 -08002078void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2079 for (const auto& event : mPendingHotplugEvents) {
2080 DisplayDevice::DisplayType displayType = event.isPrimaryDisplay
2081 ? DisplayDevice::DISPLAY_PRIMARY
2082 : DisplayDevice::DISPLAY_EXTERNAL;
2083
2084 if (mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2085 ALOGE("External displays are not supported by the vr hardware composer.");
2086 continue;
2087 }
2088
2089 mHwc->onHotplug(event.display, event.connection);
2090
2091 if (event.connection == HWC2::Connection::Connected) {
2092 createBuiltinDisplayLocked(displayType);
2093 } else {
2094 mCurrentState.displays.removeItem(mBuiltinDisplays[displayType]);
2095 mBuiltinDisplays[displayType].clear();
2096 }
2097
2098 if (displayType == DisplayDevice::DISPLAY_PRIMARY) {
2099 createDefaultDisplayDevice();
2100 }
2101
2102 processDisplayChangesLocked();
2103 }
2104
2105 mPendingHotplugEvents.clear();
2106}
2107
Lloyd Piqueb3206282017-12-14 17:00:15 -08002108void SurfaceFlinger::processDisplayChangesLocked() {
2109 // here we take advantage of Vector's copy-on-write semantics to
2110 // improve performance by skipping the transaction entirely when
2111 // know that the lists are identical
2112 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2113 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2114 if (!curr.isIdenticalTo(draw)) {
2115 mVisibleRegionsDirty = true;
2116 const size_t cc = curr.size();
2117 size_t dc = draw.size();
2118
2119 // find the displays that were removed
2120 // (ie: in drawing state but not in current state)
2121 // also handle displays that changed
2122 // (ie: displays that are in both lists)
2123 for (size_t i = 0; i < dc;) {
2124 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2125 if (j < 0) {
2126 // in drawing state but not in current state
2127 if (!draw[i].isMainDisplay()) {
2128 // Call makeCurrent() on the primary display so we can
2129 // be sure that nothing associated with this display
2130 // is current.
2131 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2132 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
2133 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2134 if (hw != NULL) hw->disconnect(getHwComposer());
2135 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2136 mEventThread->onHotplugReceived(draw[i].type, false);
2137 mDisplays.removeItem(draw.keyAt(i));
2138 } else {
2139 ALOGW("trying to remove the main display");
2140 }
2141 } else {
2142 // this display is in both lists. see if something changed.
2143 const DisplayDeviceState& state(curr[j]);
2144 const wp<IBinder>& display(curr.keyAt(j));
2145 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2146 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2147 if (state_binder != draw_binder) {
2148 // changing the surface is like destroying and
2149 // recreating the DisplayDevice, so we just remove it
2150 // from the drawing state, so that it get re-added
2151 // below.
2152 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2153 if (hw != NULL) hw->disconnect(getHwComposer());
2154 mDisplays.removeItem(display);
2155 mDrawingState.displays.removeItemsAt(i);
2156 dc--;
2157 // at this point we must loop to the next item
2158 continue;
2159 }
2160
2161 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2162 if (disp != NULL) {
2163 if (state.layerStack != draw[i].layerStack) {
2164 disp->setLayerStack(state.layerStack);
2165 }
2166 if ((state.orientation != draw[i].orientation) ||
2167 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2168 disp->setProjection(state.orientation, state.viewport, state.frame);
2169 }
2170 if (state.width != draw[i].width || state.height != draw[i].height) {
2171 disp->setDisplaySize(state.width, state.height);
2172 }
2173 }
2174 }
2175 ++i;
2176 }
2177
2178 // find displays that were added
2179 // (ie: in current state but not in drawing state)
2180 for (size_t i = 0; i < cc; i++) {
2181 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2182 const DisplayDeviceState& state(curr[i]);
2183
2184 sp<DisplaySurface> dispSurface;
2185 sp<IGraphicBufferProducer> producer;
2186 sp<IGraphicBufferProducer> bqProducer;
2187 sp<IGraphicBufferConsumer> bqConsumer;
2188 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
2189
2190 int32_t hwcId = -1;
2191 if (state.isVirtualDisplay()) {
2192 // Virtual displays without a surface are dormant:
2193 // they have external state (layer stack, projection,
2194 // etc.) but no internal state (i.e. a DisplayDevice).
2195 if (state.surface != NULL) {
2196 // Allow VR composer to use virtual displays.
2197 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
2198 int width = 0;
2199 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2200 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2201 int height = 0;
2202 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2203 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2204 int intFormat = 0;
2205 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2206 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2207 auto format = static_cast<android_pixel_format_t>(intFormat);
2208
2209 mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2210 }
2211
2212 // TODO: Plumb requested format back up to consumer
2213
2214 sp<VirtualDisplaySurface> vds =
2215 new VirtualDisplaySurface(*mHwc, hwcId, state.surface, bqProducer,
2216 bqConsumer, state.displayName);
2217
2218 dispSurface = vds;
2219 producer = vds;
2220 }
2221 } else {
2222 ALOGE_IF(state.surface != NULL,
2223 "adding a supported display, but rendering "
2224 "surface is provided (%p), ignoring it",
2225 state.surface.get());
2226
2227 hwcId = state.type;
2228 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2229 producer = bqProducer;
2230 }
2231
2232 const wp<IBinder>& display(curr.keyAt(i));
2233 if (dispSurface != NULL) {
2234 sp<DisplayDevice> hw =
2235 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2236 dispSurface, producer, mRenderEngine->getEGLConfig(),
2237 hasWideColorDisplay);
2238 hw->setLayerStack(state.layerStack);
2239 hw->setProjection(state.orientation, state.viewport, state.frame);
2240 hw->setDisplayName(state.displayName);
2241 mDisplays.add(display, hw);
2242 if (!state.isVirtualDisplay()) {
2243 mEventThread->onHotplugReceived(state.type, true);
2244 }
2245 }
2246 }
2247 }
2248 }
Lloyd Pique3e3d28c2017-12-14 17:11:26 -08002249
2250 mDrawingState.displays = mCurrentState.displays;
Lloyd Piqueb3206282017-12-14 17:00:15 -08002251}
2252
Mathias Agopian87baae12012-07-31 12:38:26 -07002253void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002254{
Dan Stoza7dde5992015-05-22 09:51:44 -07002255 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002256 mCurrentState.traverseInZOrder([](Layer* layer) {
2257 layer->notifyAvailableFrames();
2258 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002259
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002260 /*
2261 * Traversal of the children
2262 * (perform the transaction for each of them if needed)
2263 */
2264
Mathias Agopian3559b072012-08-15 13:46:03 -07002265 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002266 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002267 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002268 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002269
2270 const uint32_t flags = layer->doTransaction(0);
2271 if (flags & Layer::eVisibleRegion)
2272 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002273 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002274 }
2275
2276 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002277 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002278 */
2279
Mathias Agopiane57f2922012-08-09 16:29:12 -07002280 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Piqueb3206282017-12-14 17:00:15 -08002281 processDisplayChangesLocked();
Lloyd Pique3e3d28c2017-12-14 17:11:26 -08002282 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002283 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002284
Mathias Agopian84300952012-11-21 16:02:13 -08002285 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2286 // The transform hint might have changed for some layers
2287 // (either because a display has changed, or because a layer
2288 // as changed).
2289 //
2290 // Walk through all the layers in currentLayers,
2291 // and update their transform hint.
2292 //
2293 // If a layer is visible only on a single display, then that
2294 // display is used to calculate the hint, otherwise we use the
2295 // default display.
2296 //
2297 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2298 // the hint is set before we acquire a buffer from the surface texture.
2299 //
2300 // NOTE: layer transactions have taken place already, so we use their
2301 // drawing state. However, SurfaceFlinger's own transaction has not
2302 // happened yet, so we must use the current state layer list
2303 // (soon to become the drawing state list).
2304 //
2305 sp<const DisplayDevice> disp;
2306 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002307 bool first = true;
2308 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002309 // NOTE: we rely on the fact that layers are sorted by
2310 // layerStack first (so we don't have to traverse the list
2311 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002312 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002313 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002314 currentlayerStack = layerStack;
2315 // figure out if this layerstack is mirrored
2316 // (more than one display) if so, pick the default display,
2317 // if not, pick the only display it's on.
2318 disp.clear();
2319 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2320 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002321 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002322 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002323 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002324 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002325 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002326 break;
2327 }
2328 }
2329 }
2330 }
Chet Haase91d25932013-04-11 15:24:55 -07002331 if (disp == NULL) {
2332 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2333 // redraw after transform hint changes. See bug 8508397.
2334
2335 // could be null when this layer is using a layerStack
2336 // that is not visible on any display. Also can occur at
2337 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002338 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002339 }
Chet Haase91d25932013-04-11 15:24:55 -07002340 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002341
2342 first = false;
2343 });
Mathias Agopian84300952012-11-21 16:02:13 -08002344 }
2345
2346
Mathias Agopian3559b072012-08-15 13:46:03 -07002347 /*
2348 * Perform our own transaction if needed
2349 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002350
2351 if (mLayersAdded) {
2352 mLayersAdded = false;
2353 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002354 mVisibleRegionsDirty = true;
2355 }
2356
2357 // some layers might have been removed, so
2358 // we need to update the regions they're exposing.
2359 if (mLayersRemoved) {
2360 mLayersRemoved = false;
2361 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002362 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002363 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002364 // this layer is not visible anymore
2365 // TODO: we could traverse the tree from front to back and
2366 // compute the actual visible region
2367 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002368 Region visibleReg;
2369 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002370 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002371 }
Robert Carr2047fae2016-11-28 14:09:09 -08002372 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002373 }
2374
2375 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002376
2377 updateCursorAsync();
2378}
2379
2380void SurfaceFlinger::updateCursorAsync()
2381{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002382 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2383 auto& displayDevice = mDisplays[displayId];
2384 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002385 continue;
2386 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002387
2388 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2389 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002390 }
2391 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002392}
2393
2394void SurfaceFlinger::commitTransaction()
2395{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002396 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002397 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002398 for (const auto& l : mLayersPendingRemoval) {
2399 recordBufferingStats(l->getName().string(),
2400 l->getOccupancyHistory(true));
2401 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002402 }
2403 mLayersPendingRemoval.clear();
2404 }
2405
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002406 // If this transaction is part of a window animation then the next frame
2407 // we composite should be considered an animation as well.
2408 mAnimCompositionPending = mAnimTransactionPending;
2409
Mathias Agopian4fec8732012-06-29 14:12:52 -07002410 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002411 mDrawingState.traverseInZOrder([](Layer* layer) {
2412 layer->commitChildList();
2413 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002414 mTransactionPending = false;
2415 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002416 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002417}
2418
Chia-I Wuab0c3192017-08-01 11:29:00 -07002419void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002420 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002421{
Mathias Agopian841cde52012-03-01 15:44:37 -08002422 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002423 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002424
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002425 Region aboveOpaqueLayers;
2426 Region aboveCoveredLayers;
2427 Region dirty;
2428
Mathias Agopian87baae12012-07-31 12:38:26 -07002429 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002430
Robert Carr2047fae2016-11-28 14:09:09 -08002431 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002432 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002433 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002434
Jesse Hall01e29052013-02-19 16:13:35 -08002435 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002436 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002437 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002438
Mathias Agopianab028732010-03-16 16:41:46 -07002439 /*
2440 * opaqueRegion: area of a surface that is fully opaque.
2441 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002442 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002443
2444 /*
2445 * visibleRegion: area of a surface that is visible on screen
2446 * and not fully transparent. This is essentially the layer's
2447 * footprint minus the opaque regions above it.
2448 * Areas covered by a translucent surface are considered visible.
2449 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002451
2452 /*
2453 * coveredRegion: area of a surface that is covered by all
2454 * visible regions above it (which includes the translucent areas).
2455 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002457
Jesse Halla8026d22012-09-25 13:25:04 -07002458 /*
2459 * transparentRegion: area of a surface that is hinted to be completely
2460 * transparent. This is only used to tell when the layer has no visible
2461 * non-transparent regions and can be removed from the layer list. It
2462 * does not affect the visibleRegion of this layer or any layers
2463 * beneath it. The hint may not be correct if apps don't respect the
2464 * SurfaceView restrictions (which, sadly, some don't).
2465 */
2466 Region transparentRegion;
2467
Mathias Agopianab028732010-03-16 16:41:46 -07002468
2469 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002470 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002471 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002472 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002474 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002475 if (!visibleRegion.isEmpty()) {
2476 // Remove the transparent area from the visible region
2477 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002478 if (tr.preserveRects()) {
2479 // transform the transparent region
2480 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002481 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002482 // transformation too complex, can't do the
2483 // transparent region optimization.
2484 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002485 }
Mathias Agopianab028732010-03-16 16:41:46 -07002486 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487
Mathias Agopianab028732010-03-16 16:41:46 -07002488 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002489 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002490 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002491 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2492 // the opaque region is the layer's footprint
2493 opaqueRegion = visibleRegion;
2494 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495 }
2496 }
2497
Mathias Agopianab028732010-03-16 16:41:46 -07002498 // Clip the covered region to the visible region
2499 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2500
2501 // Update aboveCoveredLayers for next (lower) layer
2502 aboveCoveredLayers.orSelf(visibleRegion);
2503
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504 // subtract the opaque region covered by the layers above us
2505 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506
2507 // compute this layer's dirty region
2508 if (layer->contentDirty) {
2509 // we need to invalidate the whole region
2510 dirty = visibleRegion;
2511 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002512 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002513 layer->contentDirty = false;
2514 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002515 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002516 * the exposed region consists of two components:
2517 * 1) what's VISIBLE now and was COVERED before
2518 * 2) what's EXPOSED now less what was EXPOSED before
2519 *
2520 * note that (1) is conservative, we start with the whole
2521 * visible region but only keep what used to be covered by
2522 * something -- which mean it may have been exposed.
2523 *
2524 * (2) handles areas that were not covered by anything but got
2525 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002526 */
Mathias Agopianab028732010-03-16 16:41:46 -07002527 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002528 const Region oldVisibleRegion = layer->visibleRegion;
2529 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002530 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2531 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002532 }
2533 dirty.subtractSelf(aboveOpaqueLayers);
2534
2535 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002536 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002537
Mathias Agopianab028732010-03-16 16:41:46 -07002538 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002540
Jesse Halla8026d22012-09-25 13:25:04 -07002541 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002542 layer->setVisibleRegion(visibleRegion);
2543 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002544 layer->setVisibleNonTransparentRegion(
2545 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002546 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547
Mathias Agopian87baae12012-07-31 12:38:26 -07002548 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549}
2550
Chia-I Wuab0c3192017-08-01 11:29:00 -07002551void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002552 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002553 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002554 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002555 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002556 }
2557 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002558}
2559
Dan Stoza6b9454d2014-11-07 16:00:59 -08002560bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002562 ALOGV("handlePageFlip");
2563
Brian Andersond6927fb2016-07-23 23:37:30 -07002564 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565
Mathias Agopian4fec8732012-06-29 14:12:52 -07002566 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002567 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002568 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002569
2570 // Store the set of layers that need updates. This set must not change as
2571 // buffers are being latched, as this could result in a deadlock.
2572 // Example: Two producers share the same command stream and:
2573 // 1.) Layer 0 is latched
2574 // 2.) Layer 0 gets a new frame
2575 // 2.) Layer 1 gets a new frame
2576 // 3.) Layer 1 is latched.
2577 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2578 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002579 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002580 if (layer->hasQueuedFrame()) {
2581 frameQueued = true;
2582 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002583 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002584 } else {
2585 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002586 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002587 } else {
2588 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002589 }
Robert Carr2047fae2016-11-28 14:09:09 -08002590 });
2591
Dan Stoza9e56aa02015-11-02 13:00:03 -08002592 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002593 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002594 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002595 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002596 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002597 newDataLatched = true;
2598 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002599 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002600
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002601 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002602
2603 // If we will need to wake up at some time in the future to deal with a
2604 // queued frame that shouldn't be displayed during this vsync period, wake
2605 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002606 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002607 signalLayerUpdate();
2608 }
2609
2610 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002611 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612}
2613
Mathias Agopianad456f92011-01-13 17:53:01 -08002614void SurfaceFlinger::invalidateHwcGeometry()
2615{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002616 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002617}
2618
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002619
Fabien Sanglard830b8472016-11-30 16:35:58 -08002620void SurfaceFlinger::doDisplayComposition(
2621 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002622 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002623{
Dan Stoza71433162014-02-04 16:22:36 -08002624 // We only need to actually compose the display if:
2625 // 1) It is being handled by hardware composer, which may need this to
2626 // keep its virtual display state machine in sync, or
2627 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002628 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002629 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002630 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002631 return;
2632 }
2633
Dan Stoza9e56aa02015-11-02 13:00:03 -08002634 ALOGV("doDisplayComposition");
2635
Mathias Agopian87baae12012-07-31 12:38:26 -07002636 Region dirtyRegion(inDirtyRegion);
2637
Mathias Agopianb8a55602009-06-26 19:06:36 -07002638 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002639 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640
Fabien Sanglard830b8472016-11-30 16:35:58 -08002641 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002642 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002643 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2644 // takes a rectangle, we must make sure to update that whole
2645 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002646 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002647 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002648 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002649 // We need to redraw the rectangle that will be updated
2650 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002651 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002652 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002653 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002654 } else {
2655 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002656 dirtyRegion.set(displayDevice->bounds());
2657 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658 }
2659 }
2660
Fabien Sanglard830b8472016-11-30 16:35:58 -08002661 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002663 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002664 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002665
2666 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002667 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668}
2669
Dan Stoza9e56aa02015-11-02 13:00:03 -08002670bool SurfaceFlinger::doComposeSurfaces(
2671 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002672{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002673 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002674
Dan Stoza9e56aa02015-11-02 13:00:03 -08002675 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002676
2677 mat4 oldColorMatrix;
2678 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2679 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2680 if (applyColorMatrix) {
2681 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2682 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2683 }
2684
Dan Stoza9e56aa02015-11-02 13:00:03 -08002685 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2686 if (hasClientComposition) {
2687 ALOGV("hasClientComposition");
2688
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002689#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002690 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002691 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002692#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002694 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002695 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002696 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002697
2698 // |mStateLock| not needed as we are on the main thread
2699 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002700 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2701 }
2702 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002703 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002704
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002705 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002706 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2707 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002708 // when using overlays, we assume a fully transparent framebuffer
2709 // NOTE: we could reduce how much we need to clear, for instance
2710 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002711 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002712 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002713 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002714 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002715 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002716 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002717
2718 // we remove the scissor part
2719 // we're left with the letterbox region
2720 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002721 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002722
2723 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002724 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002725
2726 // but limit it to the dirty region
2727 region.andSelf(dirty);
2728
Mathias Agopianb9494d52012-04-18 02:28:45 -07002729 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002730 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002731 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002732 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002733 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002734 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002735
Dan Stoza9e56aa02015-11-02 13:00:03 -08002736 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002737 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002738 // scissor on the main display. It should never be needed
2739 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 const Rect& bounds(displayDevice->getBounds());
2741 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002742 if (scissor != bounds) {
2743 // scissor doesn't match the screen's dimensions, so we
2744 // need to clear everything outside of it and enable
2745 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002746
Mathias Agopianf45c5102012-10-24 16:29:17 -07002747 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002748 const uint32_t height = displayDevice->getHeight();
2749 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002750 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002751 }
2752 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002753 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002754
Mathias Agopian85d751c2012-08-29 16:59:24 -07002755 /*
2756 * and then, render the layers targeted at the framebuffer
2757 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002758
Dan Stoza9e56aa02015-11-02 13:00:03 -08002759 ALOGV("Rendering client layers");
2760 const Transform& displayTransform = displayDevice->getTransform();
2761 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002762 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002763 bool firstLayer = true;
2764 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2765 const Region clip(dirty.intersect(
2766 displayTransform.transform(layer->visibleRegion)));
2767 ALOGV("Layer: %s", layer->getName().string());
2768 ALOGV(" Composition type: %s",
2769 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002770 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 switch (layer->getCompositionType(hwcId)) {
2772 case HWC2::Composition::Cursor:
2773 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002774 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002775 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002776 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002777 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2778 layer->isOpaque(state) && (state.alpha == 1.0f)
2779 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002780 // never clear the very first layer since we're
2781 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002782 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002783 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002784 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002785 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002786 case HWC2::Composition::Client: {
2787 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002788 break;
2789 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002790 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002791 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002792 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002793 } else {
2794 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002795 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002796 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002797 }
2798 } else {
2799 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002800 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002801 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002802 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002803 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002804 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002805 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002806 }
2807 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002808
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002809 if (applyColorMatrix) {
2810 getRenderEngine().setupColorTransform(oldColorMatrix);
2811 }
2812
Mathias Agopianf45c5102012-10-24 16:29:17 -07002813 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002814 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002815 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002816}
2817
Fabien Sanglard830b8472016-11-30 16:35:58 -08002818void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2819 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002820 RenderEngine& engine(getRenderEngine());
2821 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822}
2823
Dan Stoza7d89d062015-04-30 13:29:25 -07002824status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002825 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002826 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002827 const sp<Layer>& lbc,
2828 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002829{
Dan Stoza7d89d062015-04-30 13:29:25 -07002830 // add this layer to the current state list
2831 {
2832 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002833 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002834 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2835 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002836 return NO_MEMORY;
2837 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002838 if (parent == nullptr) {
2839 mCurrentState.layersSortedByZ.add(lbc);
2840 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002841 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2842 ALOGE("addClientLayer called with a removed parent");
2843 return NAME_NOT_FOUND;
2844 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002845 parent->addChild(lbc);
2846 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002847
Dan Stoza7d89d062015-04-30 13:29:25 -07002848 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002849 mLayersAdded = true;
2850 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002851 }
2852
Mathias Agopian96f08192010-06-02 23:28:45 -07002853 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002854 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002855
Dan Stoza7d89d062015-04-30 13:29:25 -07002856 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002857}
2858
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002859status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002860 Mutex::Autolock _l(mStateLock);
2861
Robert Carr1f0a16a2016-10-24 16:27:39 -07002862 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002863 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002864 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002865 if (topLevelOnly) {
2866 return NO_ERROR;
2867 }
2868
Chia-I Wu98f1c102017-05-30 14:54:08 -07002869 sp<Layer> ancestor = p;
2870 while (ancestor->getParent() != nullptr) {
2871 ancestor = ancestor->getParent();
2872 }
2873 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2874 ALOGE("removeLayer called with a layer whose parent has been removed");
2875 return NAME_NOT_FOUND;
2876 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002877
2878 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002879 } else {
2880 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002881 }
2882
Robert Carr136e2f62017-02-08 17:54:29 -08002883 // As a matter of normal operation, the LayerCleaner will produce a second
2884 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2885 // so we will succeed in promoting it, but it's already been removed
2886 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2887 // otherwise something has gone wrong and we are leaking the layer.
2888 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002889 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2890 layer->getName().string(),
2891 (p != nullptr) ? p->getName().string() : "no-parent");
2892 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002893 } else if (index < 0) {
2894 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002895 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002896
Chia-I Wuc6657022017-08-15 11:18:17 -07002897 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002898 mLayersPendingRemoval.add(layer);
2899 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002900 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002901 setTransactionFlags(eTransactionNeeded);
2902 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002903}
2904
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002905uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002906 return android_atomic_release_load(&mTransactionFlags);
2907}
2908
Mathias Agopian3f844832013-08-07 21:24:32 -07002909uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2911}
2912
Mathias Agopian3f844832013-08-07 21:24:32 -07002913uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2915 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002916 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917 }
2918 return old;
2919}
2920
Mathias Agopian8b33f032012-07-24 20:43:54 -07002921void SurfaceFlinger::setTransactionState(
2922 const Vector<ComposerState>& state,
2923 const Vector<DisplayState>& displays,
2924 uint32_t flags)
2925{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002926 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002927 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002928 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002929
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002930 if (flags & eAnimation) {
2931 // For window updates that are part of an animation we must wait for
2932 // previous animation "frames" to be handled.
2933 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002934 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002935 if (CC_UNLIKELY(err != NO_ERROR)) {
2936 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002937 // caller after a few seconds.
2938 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2939 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002940 mAnimTransactionPending = false;
2941 break;
2942 }
2943 }
2944 }
2945
Mathias Agopiane57f2922012-08-09 16:29:12 -07002946 size_t count = displays.size();
2947 for (size_t i=0 ; i<count ; i++) {
2948 const DisplayState& s(displays[i]);
2949 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002950 }
2951
Mathias Agopiane57f2922012-08-09 16:29:12 -07002952 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002953 for (size_t i=0 ; i<count ; i++) {
2954 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002955 // Here we need to check that the interface we're given is indeed
2956 // one of our own. A malicious client could give us a NULL
2957 // IInterface, or one of its own or even one of our own but a
2958 // different type. All these situations would cause us to crash.
2959 //
2960 // NOTE: it would be better to use RTTI as we could directly check
2961 // that we have a Client*. however, RTTI is disabled in Android.
2962 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002963 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002964 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002965 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002966 sp<Client> client( static_cast<Client *>(s.client.get()) );
2967 transactionFlags |= setClientStateLocked(client, s.state);
2968 }
2969 }
2970 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002971 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002972
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002973 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2974 // anyway. This can be used as a flush mechanism for previous async transactions.
2975 // Empty animation transaction can be used to simulate back-pressure, so also force a
2976 // transaction for empty animation transactions.
2977 if (transactionFlags == 0 &&
2978 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002979 transactionFlags = eTransactionNeeded;
2980 }
2981
Mathias Agopian386aa982011-11-07 21:58:03 -08002982 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002983 if (mInterceptor.isEnabled()) {
2984 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2985 }
Irvel468051e2016-06-13 16:44:44 -07002986
Mathias Agopian386aa982011-11-07 21:58:03 -08002987 // this triggers the transaction
2988 setTransactionFlags(transactionFlags);
2989
2990 // if this is a synchronous transaction, wait for it to take effect
2991 // before returning.
2992 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002993 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002994 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002995 if (flags & eAnimation) {
2996 mAnimTransactionPending = true;
2997 }
2998 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002999 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3000 if (CC_UNLIKELY(err != NO_ERROR)) {
3001 // just in case something goes wrong in SF, return to the
3002 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003003 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3004 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003005 break;
3006 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003007 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003008 }
3009}
3010
Mathias Agopiane57f2922012-08-09 16:29:12 -07003011uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3012{
Jesse Hall9a143922012-10-04 16:29:19 -07003013 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3014 if (dpyIdx < 0)
3015 return 0;
3016
Mathias Agopiane57f2922012-08-09 16:29:12 -07003017 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003018 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003019 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003020 const uint32_t what = s.what;
3021 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003022 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003023 disp.surface = s.surface;
3024 flags |= eDisplayTransactionNeeded;
3025 }
3026 }
3027 if (what & DisplayState::eLayerStackChanged) {
3028 if (disp.layerStack != s.layerStack) {
3029 disp.layerStack = s.layerStack;
3030 flags |= eDisplayTransactionNeeded;
3031 }
3032 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003033 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003034 if (disp.orientation != s.orientation) {
3035 disp.orientation = s.orientation;
3036 flags |= eDisplayTransactionNeeded;
3037 }
3038 if (disp.frame != s.frame) {
3039 disp.frame = s.frame;
3040 flags |= eDisplayTransactionNeeded;
3041 }
3042 if (disp.viewport != s.viewport) {
3043 disp.viewport = s.viewport;
3044 flags |= eDisplayTransactionNeeded;
3045 }
3046 }
Michael Lentine47e45402014-07-18 15:34:25 -07003047 if (what & DisplayState::eDisplaySizeChanged) {
3048 if (disp.width != s.width) {
3049 disp.width = s.width;
3050 flags |= eDisplayTransactionNeeded;
3051 }
3052 if (disp.height != s.height) {
3053 disp.height = s.height;
3054 flags |= eDisplayTransactionNeeded;
3055 }
3056 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003057 }
3058 return flags;
3059}
3060
3061uint32_t SurfaceFlinger::setClientStateLocked(
3062 const sp<Client>& client,
3063 const layer_state_t& s)
3064{
3065 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003066 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003067 if (layer != 0) {
3068 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003069 bool geometryAppliesWithResize =
3070 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003071 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003072 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003073 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003074 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003075 }
3076 if (what & layer_state_t::eLayerChanged) {
3077 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003078 const auto& p = layer->getParent();
3079 if (p == nullptr) {
3080 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3081 if (layer->setLayer(s.z) && idx >= 0) {
3082 mCurrentState.layersSortedByZ.removeAt(idx);
3083 mCurrentState.layersSortedByZ.add(layer);
3084 // we need traversal (state changed)
3085 // AND transaction (list changed)
3086 flags |= eTransactionNeeded|eTraversalNeeded;
3087 }
3088 } else {
3089 if (p->setChildLayer(layer, s.z)) {
3090 flags |= eTransactionNeeded|eTraversalNeeded;
3091 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003092 }
3093 }
Robert Carrdb66e622017-04-10 16:55:57 -07003094 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003095 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003096 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003097 mCurrentState.layersSortedByZ.removeAt(idx);
3098 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003099 flags |= eTransactionNeeded|eTraversalNeeded;
3100 }
3101 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003102 if (what & layer_state_t::eSizeChanged) {
3103 if (layer->setSize(s.w, s.h)) {
3104 flags |= eTraversalNeeded;
3105 }
3106 }
3107 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003108 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003109 flags |= eTraversalNeeded;
3110 }
3111 if (what & layer_state_t::eMatrixChanged) {
3112 if (layer->setMatrix(s.matrix))
3113 flags |= eTraversalNeeded;
3114 }
3115 if (what & layer_state_t::eTransparentRegionChanged) {
3116 if (layer->setTransparentRegionHint(s.transparentRegion))
3117 flags |= eTraversalNeeded;
3118 }
Dan Stoza23116082015-06-18 14:58:39 -07003119 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003120 if (layer->setFlags(s.flags, s.mask))
3121 flags |= eTraversalNeeded;
3122 }
3123 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003124 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003125 flags |= eTraversalNeeded;
3126 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003127 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003128 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003129 flags |= eTraversalNeeded;
3130 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003131 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003132 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003133 // We only allow setting layer stacks for top level layers,
3134 // everything else inherits layer stack from its parent.
3135 if (layer->hasParent()) {
3136 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3137 layer->getName().string());
3138 } else if (idx < 0) {
3139 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3140 "that also does not appear in the top level layer list. Something"
3141 " has gone wrong.", layer->getName().string());
3142 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003143 mCurrentState.layersSortedByZ.removeAt(idx);
3144 mCurrentState.layersSortedByZ.add(layer);
3145 // we need traversal (state changed)
3146 // AND transaction (list changed)
3147 flags |= eTransactionNeeded|eTraversalNeeded;
3148 }
3149 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003150 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003151 if (s.barrierHandle != nullptr) {
3152 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3153 } else if (s.barrierGbp != nullptr) {
3154 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3155 if (authenticateSurfaceTextureLocked(gbp)) {
3156 const auto& otherLayer =
3157 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3158 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3159 } else {
3160 ALOGE("Attempt to defer transaction to to an"
3161 " unrecognized GraphicBufferProducer");
3162 }
3163 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003164 // We don't trigger a traversal here because if no other state is
3165 // changed, we don't want this to cause any more work
3166 }
Robert Carr1db73f62016-12-21 12:58:51 -08003167 if (what & layer_state_t::eReparentChildren) {
3168 if (layer->reparentChildren(s.reparentHandle)) {
3169 flags |= eTransactionNeeded|eTraversalNeeded;
3170 }
3171 }
Robert Carr9524cb32017-02-13 11:32:32 -08003172 if (what & layer_state_t::eDetachChildren) {
3173 layer->detachChildren();
3174 }
Robert Carrc3574f72016-03-24 12:19:32 -07003175 if (what & layer_state_t::eOverrideScalingModeChanged) {
3176 layer->setOverrideScalingMode(s.overrideScalingMode);
3177 // We don't trigger a traversal here because if no other state is
3178 // changed, we don't want this to cause any more work
3179 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003180 }
3181 return flags;
3182}
3183
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003184status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003185 const String8& name,
3186 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003187 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003188 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3189 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003190{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003191 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003192 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003193 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003194 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003195 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003196
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003197 status_t result = NO_ERROR;
3198
3199 sp<Layer> layer;
3200
Cody Northropbc755282017-03-31 12:00:08 -06003201 String8 uniqueName = getUniqueLayerName(name);
3202
Mathias Agopian3165cc22012-08-08 19:42:09 -07003203 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3204 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003205 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003206 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003207 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003208 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003209 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003210 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003211 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003212 handle, gbp, &layer);
3213 break;
3214 default:
3215 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216 break;
3217 }
3218
Dan Stoza7d89d062015-04-30 13:29:25 -07003219 if (result != NO_ERROR) {
3220 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003222
Chia-I Wuab0c3192017-08-01 11:29:00 -07003223 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3224 // TODO b/64227542
3225 if (windowType == 441731) {
3226 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3227 layer->setPrimaryDisplayOnly();
3228 }
3229
Albert Chaulk479c60c2017-01-27 14:21:34 -05003230 layer->setInfo(windowType, ownerUid);
3231
Robert Carr1f0a16a2016-10-24 16:27:39 -07003232 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003233 if (result != NO_ERROR) {
3234 return result;
3235 }
Irvelffc9efc2016-07-27 15:16:37 -07003236 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003237
3238 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003239 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240}
3241
Cody Northropbc755282017-03-31 12:00:08 -06003242String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3243{
3244 bool matchFound = true;
3245 uint32_t dupeCounter = 0;
3246
3247 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3248 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3249
3250 // Loop over layers until we're sure there is no matching name
3251 while (matchFound) {
3252 matchFound = false;
3253 mDrawingState.traverseInZOrder([&](Layer* layer) {
3254 if (layer->getName() == uniqueName) {
3255 matchFound = true;
3256 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3257 }
3258 });
3259 }
3260
3261 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3262
3263 return uniqueName;
3264}
3265
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003266status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3267 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3268 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003269{
3270 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003271 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003272 case PIXEL_FORMAT_TRANSPARENT:
3273 case PIXEL_FORMAT_TRANSLUCENT:
3274 format = PIXEL_FORMAT_RGBA_8888;
3275 break;
3276 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003277 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278 break;
3279 }
3280
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003281 *outLayer = new Layer(this, client, name, w, h, flags);
3282 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3283 if (err == NO_ERROR) {
3284 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003285 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003287
3288 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3289 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003290}
3291
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003292status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3293 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3294 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003295{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003296 *outLayer = new LayerDim(this, client, name, w, h, flags);
3297 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003298 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003299 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003300}
3301
Mathias Agopianac9fa422013-02-11 16:40:36 -08003302status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003303{
Robert Carr9524cb32017-02-13 11:32:32 -08003304 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003305 status_t err = NO_ERROR;
3306 sp<Layer> l(client->getLayerUser(handle));
3307 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003308 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003309 err = removeLayer(l);
3310 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3311 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003312 }
3313 return err;
3314}
3315
Mathias Agopian13127d82013-03-05 17:47:11 -08003316status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003317{
Mathias Agopian67106042013-03-14 19:18:13 -07003318 // called by ~LayerCleaner() when all references to the IBinder (handle)
3319 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003320 sp<Layer> l = layer.promote();
3321 if (l == nullptr) {
3322 // The layer has already been removed, carry on
3323 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003324 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003325 // If we have a parent, then we can continue to live as long as it does.
3326 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003327}
3328
Mathias Agopianb60314a2012-04-10 22:09:54 -07003329// ---------------------------------------------------------------------------
3330
Andy McFadden13a082e2012-08-24 10:16:42 -07003331void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003332 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003333 Vector<ComposerState> state;
3334 Vector<DisplayState> displays;
3335 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003336 d.what = DisplayState::eDisplayProjectionChanged |
3337 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003338 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003339 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003340 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003341 d.frame.makeInvalid();
3342 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003343 d.width = 0;
3344 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003345 displays.add(d);
3346 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003347 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3348 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003349
Dan Stoza9e56aa02015-11-02 13:00:03 -08003350 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3351 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003352 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003353
Brian Andersond0010582017-03-07 13:20:31 -08003354 // Use phase of 0 since phase is not known.
3355 // Use latency of 0, which will snap to the ideal latency.
3356 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003357}
3358
3359void SurfaceFlinger::initializeDisplays() {
3360 class MessageScreenInitialized : public MessageBase {
3361 SurfaceFlinger* flinger;
3362 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003363 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003364 virtual bool handler() {
3365 flinger->onInitializeDisplays();
3366 return true;
3367 }
3368 };
3369 sp<MessageBase> msg = new MessageScreenInitialized(this);
3370 postMessageAsync(msg); // we may be called from main thread, use async message
3371}
3372
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003373void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003374 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003375 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3376 this);
3377 int32_t type = hw->getDisplayType();
3378 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003379
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003380 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003381 return;
3382 }
3383
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003384 hw->setPowerMode(mode);
3385 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3386 ALOGW("Trying to set power mode for virtual display");
3387 return;
3388 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003389
Irvelffc9efc2016-07-27 15:16:37 -07003390 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003391 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003392 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3393 if (idx < 0) {
3394 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3395 return;
3396 }
3397 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3398 }
3399
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003400 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003401 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003402 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003403 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3404 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003405 // FIXME: eventthread only knows about the main display right now
3406 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003407 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003408 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003409
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003410 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003411 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003412 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003413
3414 struct sched_param param = {0};
3415 param.sched_priority = 1;
3416 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3417 ALOGW("Couldn't set SCHED_FIFO on display on");
3418 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003419 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003420 // Turn off the display
3421 struct sched_param param = {0};
3422 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3423 ALOGW("Couldn't set SCHED_OTHER on display off");
3424 }
3425
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003426 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003427 disableHardwareVsync(true); // also cancels any in-progress resync
3428
Mathias Agopiancde87a32012-09-13 14:09:01 -07003429 // FIXME: eventthread only knows about the main display right now
3430 mEventThread->onScreenReleased();
3431 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003432
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003433 getHwComposer().setPowerMode(type, mode);
3434 mVisibleRegionsDirty = true;
3435 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003436 } else if (mode == HWC_POWER_MODE_DOZE ||
3437 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003438 // Update display while dozing
3439 getHwComposer().setPowerMode(type, mode);
3440 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3441 // FIXME: eventthread only knows about the main display right now
3442 mEventThread->onScreenAcquired();
3443 resyncToHardwareVsync(true);
3444 }
3445 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3446 // Leave display going to doze
3447 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3448 disableHardwareVsync(true); // also cancels any in-progress resync
3449 // FIXME: eventthread only knows about the main display right now
3450 mEventThread->onScreenReleased();
3451 }
3452 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003453 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003454 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003455 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003456 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003457}
3458
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003459void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3460 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003461 SurfaceFlinger& mFlinger;
3462 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003463 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003464 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003465 MessageSetPowerMode(SurfaceFlinger& flinger,
3466 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3467 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003468 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003469 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003470 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003471 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003472 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003473 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003474 ALOGW("Attempt to set power mode = %d for virtual display",
3475 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003476 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003477 mFlinger.setPowerModeInternal(
3478 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003479 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003480 return true;
3481 }
3482 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003483 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003484 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003485}
3486
3487// ---------------------------------------------------------------------------
3488
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003489status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3490{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003491 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003492
Mathias Agopianbd115332013-04-18 16:41:04 -07003493 IPCThreadState* ipc = IPCThreadState::self();
3494 const int pid = ipc->getCallingPid();
3495 const int uid = ipc->getCallingUid();
3496 if ((uid != AID_SHELL) &&
3497 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003498 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003499 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003500 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003501 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003502 // (this would indicate SF is stuck, but we want to be able to
3503 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003504 status_t err = mStateLock.timedLock(s2ns(1));
3505 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003506 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003507 result.appendFormat(
3508 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3509 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003510 }
3511
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003512 bool dumpAll = true;
3513 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003514 size_t numArgs = args.size();
3515 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003516 if ((index < numArgs) &&
3517 (args[index] == String16("--list"))) {
3518 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003519 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003520 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003521 }
3522
3523 if ((index < numArgs) &&
3524 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003525 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003526 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003527 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003528 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003529
3530 if ((index < numArgs) &&
3531 (args[index] == String16("--latency-clear"))) {
3532 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003533 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003534 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003535 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003536
3537 if ((index < numArgs) &&
3538 (args[index] == String16("--dispsync"))) {
3539 index++;
3540 mPrimaryDispSync.dump(result);
3541 dumpAll = false;
3542 }
Dan Stozab90cf072015-03-05 11:05:59 -08003543
3544 if ((index < numArgs) &&
3545 (args[index] == String16("--static-screen"))) {
3546 index++;
3547 dumpStaticScreenStats(result);
3548 dumpAll = false;
3549 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003550
3551 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003552 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003553 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003554 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003555 dumpAll = false;
3556 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003557
3558 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3559 index++;
3560 dumpWideColorInfo(result);
3561 dumpAll = false;
3562 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003563 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003564
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003565 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003566 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003567 }
3568
Mathias Agopian9795c422009-08-26 16:36:26 -07003569 if (locked) {
3570 mStateLock.unlock();
3571 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572 }
3573 write(fd, result.string(), result.size());
3574 return NO_ERROR;
3575}
3576
Dan Stozac7014012014-02-14 15:03:43 -08003577void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3578 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003579{
Robert Carr2047fae2016-11-28 14:09:09 -08003580 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003581 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003582 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003583}
3584
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003585void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003586 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003587{
3588 String8 name;
3589 if (index < args.size()) {
3590 name = String8(args[index]);
3591 index++;
3592 }
3593
Dan Stoza9e56aa02015-11-02 13:00:03 -08003594 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3595 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003596 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003597
3598 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003599 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003600 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003601 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003602 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003603 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003604 }
Robert Carr2047fae2016-11-28 14:09:09 -08003605 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003606 }
3607}
3608
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003609void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003610 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003611{
3612 String8 name;
3613 if (index < args.size()) {
3614 name = String8(args[index]);
3615 index++;
3616 }
3617
Robert Carr2047fae2016-11-28 14:09:09 -08003618 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003619 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003620 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003621 }
Robert Carr2047fae2016-11-28 14:09:09 -08003622 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003623
Svetoslavd85084b2014-03-20 10:28:31 -07003624 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003625}
3626
Jamie Gennis6547ff42013-07-16 20:12:42 -07003627// This should only be called from the main thread. Otherwise it would need
3628// the lock and should use mCurrentState rather than mDrawingState.
3629void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003630 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003631 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003632 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003633
3634 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3635}
3636
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003637void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003638{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003639 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003640 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3641
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003642 if (isLayerTripleBufferingDisabled())
3643 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003644
3645 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003646 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003647 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003648 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003649 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3650 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003651 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003652}
3653
Dan Stozab90cf072015-03-05 11:05:59 -08003654void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3655{
3656 result.appendFormat("Static screen stats:\n");
3657 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3658 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3659 float percent = 100.0f *
3660 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3661 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3662 b + 1, bucketTimeSec, percent);
3663 }
3664 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3665 float percent = 100.0f *
3666 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3667 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3668 NUM_BUCKETS - 1, bucketTimeSec, percent);
3669}
3670
Dan Stozae77c7662016-05-13 11:37:28 -07003671void SurfaceFlinger::recordBufferingStats(const char* layerName,
3672 std::vector<OccupancyTracker::Segment>&& history) {
3673 Mutex::Autolock lock(mBufferingStatsMutex);
3674 auto& stats = mBufferingStats[layerName];
3675 for (const auto& segment : history) {
3676 if (!segment.usedThirdBuffer) {
3677 stats.twoBufferTime += segment.totalTime;
3678 }
3679 if (segment.occupancyAverage < 1.0f) {
3680 stats.doubleBufferedTime += segment.totalTime;
3681 } else if (segment.occupancyAverage < 2.0f) {
3682 stats.tripleBufferedTime += segment.totalTime;
3683 }
3684 ++stats.numSegments;
3685 stats.totalTime += segment.totalTime;
3686 }
3687}
3688
Brian Andersond6927fb2016-07-23 23:37:30 -07003689void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3690 result.appendFormat("Layer frame timestamps:\n");
3691
3692 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3693 const size_t count = currentLayers.size();
3694 for (size_t i=0 ; i<count ; i++) {
3695 currentLayers[i]->dumpFrameEvents(result);
3696 }
3697}
3698
Dan Stozae77c7662016-05-13 11:37:28 -07003699void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3700 result.append("Buffering stats:\n");
3701 result.append(" [Layer name] <Active time> <Two buffer> "
3702 "<Double buffered> <Triple buffered>\n");
3703 Mutex::Autolock lock(mBufferingStatsMutex);
3704 typedef std::tuple<std::string, float, float, float> BufferTuple;
3705 std::map<float, BufferTuple, std::greater<float>> sorted;
3706 for (const auto& statsPair : mBufferingStats) {
3707 const char* name = statsPair.first.c_str();
3708 const BufferingStats& stats = statsPair.second;
3709 if (stats.numSegments == 0) {
3710 continue;
3711 }
3712 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3713 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3714 stats.totalTime;
3715 float doubleBufferRatio = static_cast<float>(
3716 stats.doubleBufferedTime) / stats.totalTime;
3717 float tripleBufferRatio = static_cast<float>(
3718 stats.tripleBufferedTime) / stats.totalTime;
3719 sorted.insert({activeTime, {name, twoBufferRatio,
3720 doubleBufferRatio, tripleBufferRatio}});
3721 }
3722 for (const auto& sortedPair : sorted) {
3723 float activeTime = sortedPair.first;
3724 const BufferTuple& values = sortedPair.second;
3725 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3726 std::get<0>(values).c_str(), activeTime,
3727 std::get<1>(values), std::get<2>(values),
3728 std::get<3>(values));
3729 }
3730 result.append("\n");
3731}
3732
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003733void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3734 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3735
3736 // TODO: print out if wide-color mode is active or not
3737
3738 for (size_t d = 0; d < mDisplays.size(); d++) {
3739 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3740 int32_t hwcId = displayDevice->getHwcDisplayId();
3741 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3742 continue;
3743 }
3744
3745 result.appendFormat("Display %d color modes:\n", hwcId);
3746 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3747 for (auto&& mode : modes) {
3748 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3749 }
3750
3751 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3752 result.appendFormat(" Current color mode: %s (%d)\n",
3753 decodeColorMode(currentMode).c_str(), currentMode);
3754 }
3755 result.append("\n");
3756}
3757
Mathias Agopian74d211a2013-04-22 16:55:35 +02003758void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3759 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003760{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003761 bool colorize = false;
3762 if (index < args.size()
3763 && (args[index] == String16("--color"))) {
3764 colorize = true;
3765 index++;
3766 }
3767
3768 Colorizer colorizer(colorize);
3769
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003770 // figure out if we're stuck somewhere
3771 const nsecs_t now = systemTime();
3772 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3773 const nsecs_t inTransaction(mDebugInTransaction);
3774 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3775 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3776
3777 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003778 * Dump library configuration.
3779 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003780
3781 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003782 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003783 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003784 appendSfConfigString(result);
3785 appendUiConfigString(result);
3786 appendGuiConfigString(result);
3787 result.append("\n");
3788
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003789 result.append("\nWide-Color information:\n");
3790 dumpWideColorInfo(result);
3791
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003792 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003793 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003794 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003795 result.append(SyncFeatures::getInstance().toString());
3796 result.append("\n");
3797
Dan Stoza9e56aa02015-11-02 13:00:03 -08003798 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3799
Andy McFadden41d67d72014-04-25 16:58:34 -07003800 colorizer.bold(result);
3801 result.append("DispSync configuration: ");
3802 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003803 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003804 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003805 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003806 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003807 result.append("\n");
3808
Dan Stozab90cf072015-03-05 11:05:59 -08003809 // Dump static screen stats
3810 result.append("\n");
3811 dumpStaticScreenStats(result);
3812 result.append("\n");
3813
Dan Stozae77c7662016-05-13 11:37:28 -07003814 dumpBufferingStats(result);
3815
Andy McFadden4803b742012-09-24 19:07:20 -07003816 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003817 * Dump the visible layer list
3818 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003819 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003820 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003821 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003822 mCurrentState.traverseInZOrder([&](Layer* layer) {
Kalle Raitaa099a242017-01-11 11:17:29 -08003823 result.append(to_string(layer->getLayerDebugInfo()).c_str());
Robert Carr2047fae2016-11-28 14:09:09 -08003824 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003825
3826 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003827 * Dump Display state
3828 */
3829
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003830 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003831 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003832 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003833 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3834 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003835 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003836 }
3837
3838 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003839 * Dump SurfaceFlinger global state
3840 */
3841
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003842 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003843 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003844 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003845
Mathias Agopian888c8222012-08-04 21:10:38 -07003846 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003847 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003848
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003849 colorizer.bold(result);
3850 result.appendFormat("EGL implementation : %s\n",
3851 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3852 colorizer.reset(result);
3853 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003854 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003855
Mathias Agopian875d8e12013-06-07 15:35:48 -07003856 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003857
Mathias Agopian42977342012-08-05 00:40:46 -07003858 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003859 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3860 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003861 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003862 " last eglSwapBuffers() time: %f us\n"
3863 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003864 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003865 " refresh-rate : %f fps\n"
3866 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003867 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003868 " gpu_to_cpu_unsupported : %d\n"
3869 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003870 mLastSwapBufferTime/1000.0,
3871 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003872 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003873 1e9 / activeConfig->getVsyncPeriod(),
3874 activeConfig->getDpiX(),
3875 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003876 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003877
Mathias Agopian74d211a2013-04-22 16:55:35 +02003878 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003879 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003880
Mathias Agopian74d211a2013-04-22 16:55:35 +02003881 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003882 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003883
3884 /*
3885 * VSYNC state
3886 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003887 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003888 result.append("\n");
3889
3890 /*
3891 * HWC layer minidump
3892 */
3893 for (size_t d = 0; d < mDisplays.size(); d++) {
3894 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3895 int32_t hwcId = displayDevice->getHwcDisplayId();
3896 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3897 continue;
3898 }
3899
3900 result.appendFormat("Display %d HWC layers:\n", hwcId);
3901 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003902 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003903 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003904 });
Dan Stozae22aec72016-08-01 13:20:59 -07003905 result.append("\n");
3906 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003907
3908 /*
3909 * Dump HWComposer state
3910 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003911 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003912 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003913 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003914 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003915 result.appendFormat(" h/w composer %s\n",
3916 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003917 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003918
3919 /*
3920 * Dump gralloc state
3921 */
3922 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3923 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003924
3925 /*
3926 * Dump VrFlinger state if in use.
3927 */
3928 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3929 result.append("VrFlinger state:\n");
3930 result.append(mVrFlinger->Dump().c_str());
3931 result.append("\n");
3932 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003933}
3934
Mathias Agopian13127d82013-03-05 17:47:11 -08003935const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003936SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003937 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003938 wp<IBinder> dpy;
3939 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3940 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3941 dpy = mDisplays.keyAt(i);
3942 break;
3943 }
3944 }
3945 if (dpy == NULL) {
3946 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3947 // Just use the primary display so we have something to return
3948 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3949 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003950 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003951}
3952
Keun young Park63f165f2012-08-31 10:53:36 -07003953bool SurfaceFlinger::startDdmConnection()
3954{
3955 void* libddmconnection_dso =
3956 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3957 if (!libddmconnection_dso) {
3958 return false;
3959 }
3960 void (*DdmConnection_start)(const char* name);
3961 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003962 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003963 if (!DdmConnection_start) {
3964 dlclose(libddmconnection_dso);
3965 return false;
3966 }
3967 (*DdmConnection_start)(getServiceName());
3968 return true;
3969}
3970
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003971status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003972 switch (code) {
3973 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003974 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003975 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003976 case CLEAR_ANIMATION_FRAME_STATS:
3977 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003978 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003979 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003980 {
3981 // codes that require permission check
3982 IPCThreadState* ipc = IPCThreadState::self();
3983 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003984 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003985 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003986 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003987 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003988 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003989 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003990 break;
3991 }
Robert Carr1db73f62016-12-21 12:58:51 -08003992 /*
3993 * Calling setTransactionState is safe, because you need to have been
3994 * granted a reference to Client* and Handle* to do anything with it.
3995 *
3996 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3997 */
3998 case SET_TRANSACTION_STATE:
3999 case CREATE_SCOPED_CONNECTION:
4000 {
4001 return OK;
4002 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004003 case CAPTURE_SCREEN:
4004 {
4005 // codes that require permission check
4006 IPCThreadState* ipc = IPCThreadState::self();
4007 const int pid = ipc->getCallingPid();
4008 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004009 if ((uid != AID_GRAPHICS) &&
4010 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004011 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004012 return PERMISSION_DENIED;
4013 }
4014 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004015 }
4016 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004017 return OK;
4018}
4019
4020status_t SurfaceFlinger::onTransact(
4021 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4022{
4023 status_t credentialCheck = CheckTransactCodeCredentials(code);
4024 if (credentialCheck != OK) {
4025 return credentialCheck;
4026 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004027
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004028 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4029 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004030 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004031 IPCThreadState* ipc = IPCThreadState::self();
4032 const int uid = ipc->getCallingUid();
4033 if (CC_UNLIKELY(uid != AID_SYSTEM
4034 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004035 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004036 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004037 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004038 return PERMISSION_DENIED;
4039 }
4040 int n;
4041 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004042 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004043 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004044 return NO_ERROR;
4045 case 1002: // SHOW_UPDATES
4046 n = data.readInt32();
4047 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004048 invalidateHwcGeometry();
4049 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004050 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004051 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004052 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004053 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004054 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004055 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004056 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004057 setTransactionFlags(
4058 eTransactionNeeded|
4059 eDisplayTransactionNeeded|
4060 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004061 return NO_ERROR;
4062 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004063 case 1006:{ // send empty update
4064 signalRefresh();
4065 return NO_ERROR;
4066 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004067 case 1008: // toggle use of hw composer
4068 n = data.readInt32();
4069 mDebugDisableHWC = n ? 1 : 0;
4070 invalidateHwcGeometry();
4071 repaintEverything();
4072 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004073 case 1009: // toggle use of transform hint
4074 n = data.readInt32();
4075 mDebugDisableTransformHint = n ? 1 : 0;
4076 invalidateHwcGeometry();
4077 repaintEverything();
4078 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004079 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004080 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004081 reply->writeInt32(0);
4082 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004083 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004084 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004085 return NO_ERROR;
4086 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004087 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004088 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004089 return NO_ERROR;
4090 }
4091 case 1014: {
4092 // daltonize
4093 n = data.readInt32();
4094 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004095 case 1:
4096 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4097 break;
4098 case 2:
4099 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4100 break;
4101 case 3:
4102 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4103 break;
4104 default:
4105 mDaltonizer.setType(ColorBlindnessType::None);
4106 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004107 }
4108 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004109 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004110 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004111 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004112 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004113 invalidateHwcGeometry();
4114 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004115 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004116 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004117 case 1015: {
4118 // apply a color matrix
4119 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004120 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004121 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004122 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004123 for (size_t j = 0; j < 4; j++) {
4124 mColorMatrix[i][j] = data.readFloat();
4125 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004126 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004127 } else {
4128 mColorMatrix = mat4();
4129 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004130
4131 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4132 // the division by w in the fragment shader
4133 float4 lastRow(transpose(mColorMatrix)[3]);
4134 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4135 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4136 }
4137
Alan Viverette9c5a3332013-09-12 20:04:35 -07004138 invalidateHwcGeometry();
4139 repaintEverything();
4140 return NO_ERROR;
4141 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004142 // This is an experimental interface
4143 // Needs to be shifted to proper binder interface when we productize
4144 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004145 n = data.readInt32();
4146 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004147 return NO_ERROR;
4148 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004149 case 1017: {
4150 n = data.readInt32();
4151 mForceFullDamage = static_cast<bool>(n);
4152 return NO_ERROR;
4153 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004154 case 1018: { // Modify Choreographer's phase offset
4155 n = data.readInt32();
4156 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4157 return NO_ERROR;
4158 }
4159 case 1019: { // Modify SurfaceFlinger's phase offset
4160 n = data.readInt32();
4161 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4162 return NO_ERROR;
4163 }
Irvel468051e2016-06-13 16:44:44 -07004164 case 1020: { // Layer updates interceptor
4165 n = data.readInt32();
4166 if (n) {
4167 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004168 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004169 }
4170 else{
4171 ALOGV("Interceptor disabled");
4172 mInterceptor.disable();
4173 }
4174 return NO_ERROR;
4175 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004176 case 1021: { // Disable HWC virtual displays
4177 n = data.readInt32();
4178 mUseHwcVirtualDisplays = !n;
4179 return NO_ERROR;
4180 }
Romain Guy0147a172017-06-01 13:53:56 -07004181 case 1022: { // Set saturation boost
4182 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4183
4184 invalidateHwcGeometry();
4185 repaintEverything();
4186 return NO_ERROR;
4187 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004188 }
4189 }
4190 return err;
4191}
4192
Steven Thomas6d8110b2017-08-31 18:24:21 -07004193void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004194 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004195 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004196}
4197
Steven Thomas6d8110b2017-08-31 18:24:21 -07004198void SurfaceFlinger::repaintEverything() {
4199 ConditionalLock _l(mStateLock,
4200 std::this_thread::get_id() != mMainThreadId);
4201 repaintEverythingLocked();
4202}
4203
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004204// Checks that the requested width and height are valid and updates them to the display dimensions
4205// if they are set to 0
4206static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4207 Transform::orientation_flags rotation,
4208 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4209 // get screen geometry
4210 uint32_t displayWidth = displayDevice->getWidth();
4211 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004212
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004213 if (rotation & Transform::ROT_90) {
4214 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004215 }
4216
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004217 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4218 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4219 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4220 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004221 }
4222
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004223 if (*requestedWidth == 0) {
4224 *requestedWidth = displayWidth;
4225 }
4226 if (*requestedHeight == 0) {
4227 *requestedHeight = displayHeight;
4228 }
4229
4230 return NO_ERROR;
4231}
4232
4233// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4234class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004235public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004236 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4237 ~WindowDisconnector() {
4238 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004239 }
4240
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004241private:
4242 ANativeWindow* mWindow;
4243 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004244};
4245
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004246static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4247 uint32_t requestedHeight, bool hasWideColorDisplay,
4248 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4249 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4250 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4251
4252 int err = 0;
4253 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4254 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4255 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4256 err |= native_window_set_usage(window, usage);
4257
4258 if (hasWideColorDisplay) {
4259 err |= native_window_set_buffers_data_space(window,
4260 renderEngineUsesWideColor
4261 ? HAL_DATASPACE_DISPLAY_P3
4262 : HAL_DATASPACE_V0_SRGB);
4263 }
4264
4265 if (err != NO_ERROR) {
4266 return BAD_VALUE;
4267 }
4268
4269 /* TODO: Once we have the sync framework everywhere this can use
4270 * server-side waits on the fence that dequeueBuffer returns.
4271 */
4272 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4273 if (err != NO_ERROR) {
4274 return err;
4275 }
4276
4277 return NO_ERROR;
4278}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004279
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004280status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4281 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004282 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004283 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004284 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004285 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004286
4287 if (CC_UNLIKELY(display == 0))
4288 return BAD_VALUE;
4289
4290 if (CC_UNLIKELY(producer == 0))
4291 return BAD_VALUE;
4292
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004293 // if we have secure windows on this display, never allow the screen capture
4294 // unless the producer interface is local (i.e.: we can take a screenshot for
4295 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004296 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004297
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004298 // Convert to surfaceflinger's internal rotation type.
4299 Transform::orientation_flags rotationFlags;
4300 switch (rotation) {
4301 case ISurfaceComposer::eRotateNone:
4302 rotationFlags = Transform::ROT_0;
4303 break;
4304 case ISurfaceComposer::eRotate90:
4305 rotationFlags = Transform::ROT_90;
4306 break;
4307 case ISurfaceComposer::eRotate180:
4308 rotationFlags = Transform::ROT_180;
4309 break;
4310 case ISurfaceComposer::eRotate270:
4311 rotationFlags = Transform::ROT_270;
4312 break;
4313 default:
4314 rotationFlags = Transform::ROT_0;
4315 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4316 break;
4317 }
4318
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004319 { // Autolock scope
4320 Mutex::Autolock lock(mStateLock);
4321 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4322 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004323 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004324
4325 // create a surface (because we're a producer, and we need to
4326 // dequeue/queue a buffer)
4327 sp<Surface> surface = new Surface(producer, false);
4328
4329 // Put the screenshot Surface into async mode so that
4330 // Layer::headFenceHasSignaled will always return true and we'll latch the
4331 // first buffer regardless of whether or not its acquire fence has
4332 // signaled. This is needed to avoid a race condition in the rotation
4333 // animation. See b/30209608
4334 surface->setAsyncMode(true);
4335
4336 ANativeWindow* window = surface.get();
4337
4338 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4339 if (result != NO_ERROR) {
4340 return result;
4341 }
4342 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4343
4344 ANativeWindowBuffer* buffer = nullptr;
4345 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4346 getRenderEngine().usesWideColor(), &buffer);
4347 if (result != NO_ERROR) {
4348 return result;
4349 }
4350
4351 // This mutex protects syncFd and captureResult for communication of the return values from the
4352 // main thread back to this Binder thread
4353 std::mutex captureMutex;
4354 std::condition_variable captureCondition;
4355 std::unique_lock<std::mutex> captureLock(captureMutex);
4356 int syncFd = -1;
4357 std::optional<status_t> captureResult;
4358
4359 sp<LambdaMessage> message = new LambdaMessage([&]() {
4360 // If there is a refresh pending, bug out early and tell the binder thread to try again
4361 // after the refresh.
4362 if (mRefreshPending) {
4363 ATRACE_NAME("Skipping screenshot for now");
4364 std::unique_lock<std::mutex> captureLock(captureMutex);
4365 captureResult = std::make_optional<status_t>(EAGAIN);
4366 captureCondition.notify_one();
4367 return;
4368 }
4369
4370 status_t result = NO_ERROR;
4371 int fd = -1;
4372 {
4373 Mutex::Autolock _l(mStateLock);
4374 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4375 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4376 minLayerZ, maxLayerZ, useIdentityTransform,
4377 rotationFlags, isLocalScreenshot, &fd);
4378 }
4379
4380 {
4381 std::unique_lock<std::mutex> captureLock(captureMutex);
4382 syncFd = fd;
4383 captureResult = std::make_optional<status_t>(result);
4384 captureCondition.notify_one();
4385 }
4386 });
4387
4388 result = postMessageAsync(message);
4389 if (result == NO_ERROR) {
4390 captureCondition.wait(captureLock, [&]() { return captureResult; });
4391 while (*captureResult == EAGAIN) {
4392 captureResult.reset();
4393 result = postMessageAsync(message);
4394 if (result != NO_ERROR) {
4395 return result;
4396 }
4397 captureCondition.wait(captureLock, [&]() { return captureResult; });
4398 }
4399 result = *captureResult;
4400 }
4401
4402 if (result == NO_ERROR) {
4403 // queueBuffer takes ownership of syncFd
4404 result = window->queueBuffer(window, buffer, syncFd);
4405 }
4406
4407 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004408}
4409
Mathias Agopian180f10d2013-04-10 22:55:41 -07004410
4411void SurfaceFlinger::renderScreenImplLocked(
4412 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004413 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004414 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004415 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004416{
4417 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004418 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004419
4420 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004421 const int32_t hw_w = hw->getWidth();
4422 const int32_t hw_h = hw->getHeight();
4423 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004424 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004425
Dan Stozac1879002014-05-22 15:59:05 -07004426 // if a default or invalid sourceCrop is passed in, set reasonable values
4427 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4428 !sourceCrop.isValid()) {
4429 sourceCrop.setLeftTop(Point(0, 0));
4430 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4431 }
4432
4433 // ensure that sourceCrop is inside screen
4434 if (sourceCrop.left < 0) {
4435 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4436 }
Dan Stozabe31f442014-06-11 11:20:54 -07004437 if (sourceCrop.right > hw_w) {
4438 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004439 }
4440 if (sourceCrop.top < 0) {
4441 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4442 }
Dan Stozabe31f442014-06-11 11:20:54 -07004443 if (sourceCrop.bottom > hw_h) {
4444 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004445 }
4446
Romain Guy88d37dd2017-05-26 17:57:05 -07004447#ifdef USE_HWC2
4448 engine.setWideColor(hw->getWideColorSupport());
4449 engine.setColorMode(hw->getActiveColorMode());
4450#endif
4451
Mathias Agopian180f10d2013-04-10 22:55:41 -07004452 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004453 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004454
4455 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004456 engine.setViewportAndProjection(
4457 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004458 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004459
4460 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004461 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004462
Robert Carr1f0a16a2016-10-24 16:27:39 -07004463 // We loop through the first level of layers without traversing,
4464 // as we need to interpret min/max layer Z in the top level Z space.
4465 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004466 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004467 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004468 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004469 const Layer::State& state(layer->getDrawingState());
4470 if (state.z < minLayerZ || state.z > maxLayerZ) {
4471 continue;
4472 }
Dan Stoza412903f2017-04-27 13:42:17 -07004473 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004474 if (!layer->isVisible()) {
4475 return;
4476 }
4477 if (filtering) layer->setFiltering(true);
4478 layer->draw(hw, useIdentityTransform);
4479 if (filtering) layer->setFiltering(false);
4480 });
4481 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004482
Mathias Agopian931bda12013-08-28 18:11:46 -07004483 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004484}
4485
Dan Stozaabcda352017-06-01 14:37:39 -07004486// A simple RAII class that holds an EGLImage and destroys it either:
4487// a) When the destroy() method is called
4488// b) When the object goes out of scope
4489class ImageHolder {
4490public:
4491 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4492 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004493
Dan Stozaabcda352017-06-01 14:37:39 -07004494 void destroy() {
4495 if (mImage != EGL_NO_IMAGE_KHR) {
4496 eglDestroyImageKHR(mDisplay, mImage);
4497 mImage = EGL_NO_IMAGE_KHR;
4498 }
4499 }
4500
4501private:
4502 const EGLDisplay mDisplay;
4503 EGLImageKHR mImage;
4504};
4505
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004506status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4507 ANativeWindowBuffer* buffer, Rect sourceCrop,
4508 uint32_t reqWidth, uint32_t reqHeight,
4509 int32_t minLayerZ, int32_t maxLayerZ,
4510 bool useIdentityTransform,
4511 Transform::orientation_flags rotation,
4512 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004513 ATRACE_CALL();
4514
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004515 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004516 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004517 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004518 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004519 (state.z < minLayerZ || state.z > maxLayerZ)) {
4520 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004521 }
Dan Stoza412903f2017-04-27 13:42:17 -07004522 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004523 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4524 layer->isSecure());
4525 });
4526 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004527
4528 if (!isLocalScreenshot && secureLayerIsVisible) {
4529 ALOGW("FB is protected: PERMISSION_DENIED");
4530 return PERMISSION_DENIED;
4531 }
4532
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004533 int syncFd = -1;
4534 // create an EGLImage from the buffer so we can later
4535 // turn it into a texture
4536 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4537 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4538 if (image == EGL_NO_IMAGE_KHR) {
4539 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004540 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004541
Dan Stozaabcda352017-06-01 14:37:39 -07004542 // This will automatically destroy the image if we return before calling its destroy method
4543 ImageHolder imageHolder(mEGLDisplay, image);
4544
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004545 // this binds the given EGLImage as a framebuffer for the
4546 // duration of this scope.
4547 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004548 if (imageBond.getStatus() != NO_ERROR) {
4549 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004550 return INVALID_OPERATION;
4551 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004552
Dan Stozaabcda352017-06-01 14:37:39 -07004553 // this will in fact render into our dequeued buffer
4554 // via an FBO, which means we didn't have to create
4555 // an EGLSurface and therefore we're not
4556 // dependent on the context's EGLConfig.
4557 renderScreenImplLocked(
4558 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4559 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004560
Dan Stozaabcda352017-06-01 14:37:39 -07004561 // Attempt to create a sync khr object that can produce a sync point. If that
4562 // isn't available, create a non-dupable sync object in the fallback path and
4563 // wait on it directly.
4564 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4565 if (!DEBUG_SCREENSHOTS) {
4566 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4567 // native fence fd will not be populated until flush() is done.
4568 getRenderEngine().flush();
4569 }
4570
4571 if (sync != EGL_NO_SYNC_KHR) {
4572 // get the sync fd
4573 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4574 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4575 ALOGW("captureScreen: failed to dup sync khr object");
4576 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004577 }
Dan Stozaabcda352017-06-01 14:37:39 -07004578 eglDestroySyncKHR(mEGLDisplay, sync);
4579 } else {
4580 // fallback path
4581 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004582 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004583 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4584 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4585 EGLint eglErr = eglGetError();
4586 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4587 ALOGW("captureScreen: fence wait timed out");
4588 } else {
4589 ALOGW_IF(eglErr != EGL_SUCCESS,
4590 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004591 }
4592 eglDestroySyncKHR(mEGLDisplay, sync);
4593 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004594 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004595 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004596 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004597 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004598
4599 if (DEBUG_SCREENSHOTS) {
4600 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4601 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4602 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4603 hw, minLayerZ, maxLayerZ);
4604 delete [] pixels;
4605 }
4606
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004607 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004608 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004609
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004610 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004611}
4612
Mathias Agopiand5556842013-09-19 17:08:37 -07004613void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004614 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004615 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004616 for (size_t y=0 ; y<h ; y++) {
4617 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4618 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004619 if (p[x] != 0xFF000000) return;
4620 }
4621 }
4622 ALOGE("*** we just took a black screenshot ***\n"
4623 "requested minz=%d, maxz=%d, layerStack=%d",
4624 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004625
Robert Carr2047fae2016-11-28 14:09:09 -08004626 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004627 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004628 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004629 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004630 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004631 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004632 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4633 layer->isVisible() ? '+' : '-',
4634 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004635 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004636 i++;
4637 });
4638 }
4639 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004640 }
4641}
4642
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004643// ---------------------------------------------------------------------------
4644
Dan Stoza412903f2017-04-27 13:42:17 -07004645void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4646 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004647}
4648
Dan Stoza412903f2017-04-27 13:42:17 -07004649void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4650 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004651}
4652
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004653}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004654
4655
4656#if defined(__gl_h_)
4657#error "don't include gl/gl.h in this file"
4658#endif
4659
4660#if defined(__gl2_h_)
4661#error "don't include gl2/gl2.h in this file"
4662#endif