blob: 6c50fa9585125ff956d0b3ba5686ee323251cabf [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 Piquea07f6cd2018-05-31 11:43:52 -07001338 if (std::this_thread::get_id() == mMainThreadId) {
1339 // Process all pending hot plug events immediately if we are on the main thread.
1340 processDisplayHotplugEventsLocked();
1341 }
1342
Lloyd Pique3e3d28c2017-12-14 17:11:26 -08001343 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001344}
1345
Steven Thomasb02664d2017-07-26 18:48:28 -07001346void SurfaceFlinger::onRefreshReceived(int sequenceId,
1347 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001348 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001349 if (sequenceId != mComposerSequenceId) {
1350 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001351 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001352 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001353}
1354
Dan Stoza9e56aa02015-11-02 13:00:03 -08001355void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001356 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001357 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001358 getHwComposer().setVsyncEnabled(disp,
1359 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001360}
1361
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001362// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001363void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001364 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001365 // Clear the drawing state so that the logic inside of
1366 // handleTransactionLocked will fire. It will determine the delta between
1367 // mCurrentState and mDrawingState and re-apply all changes when we make the
1368 // transition.
1369 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001370 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001371 mDisplays.clear();
1372}
1373
Steven Thomas050b2c82017-03-06 11:45:16 -08001374void SurfaceFlinger::updateVrFlinger() {
1375 if (!mVrFlinger)
1376 return;
1377 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1378 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001379 return;
1380 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001381
Steven Thomasb02664d2017-07-26 18:48:28 -07001382 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1383 ALOGE("Vr flinger is only supported for remote hardware composer"
1384 " service connections. Ignoring request to transition to vr"
1385 " flinger.");
1386 mVrFlingerRequestsDisplay = false;
1387 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001388 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001390 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001391
Steven Thomasb02664d2017-07-26 18:48:28 -07001392 int currentDisplayPowerMode = getDisplayDeviceLocked(
1393 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001394
Steven Thomasb02664d2017-07-26 18:48:28 -07001395 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001396 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001397 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001398
Steven Thomasb02664d2017-07-26 18:48:28 -07001399 resetDisplayState();
1400 mHwc.reset(); // Delete the current instance before creating the new one
1401 mHwc.reset(new HWComposer(
1402 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1403 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001404
Steven Thomasb02664d2017-07-26 18:48:28 -07001405 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1406 "Switched to non-remote hardware composer");
1407
1408 if (vrFlingerRequestsDisplay) {
1409 mVrFlinger->GrantDisplayOwnership();
1410 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001411 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001412 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001413
1414 mVisibleRegionsDirty = true;
1415 invalidateHwcGeometry();
1416
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001417 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1419 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1420 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001421
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 // Reset the timing values to account for the period of the swapped in HWC
1423 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1424 const nsecs_t period = activeConfig->getVsyncPeriod();
1425 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001426
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 // Use phase of 0 since phase is not known.
1428 // Use latency of 0, which will snap to the ideal latency.
1429 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001430
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001431 android_atomic_or(1, &mRepaintEverything);
1432 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001433}
1434
Mathias Agopian4fec8732012-06-29 14:12:52 -07001435void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001436 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001437 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001438 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001439 bool frameMissed = !mHadClientComposition &&
1440 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001441 (mPreviousPresentFence->getSignalTime() ==
1442 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001443 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001444 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001445 signalLayerUpdate();
1446 break;
1447 }
1448
Steven Thomas050b2c82017-03-06 11:45:16 -08001449 // Now that we're going to make it to the handleMessageTransaction()
1450 // call below it's safe to call updateVrFlinger(), which will
1451 // potentially trigger a display handoff.
1452 updateVrFlinger();
1453
Dan Stoza6b9454d2014-11-07 16:00:59 -08001454 bool refreshNeeded = handleMessageTransaction();
1455 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001456 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001457 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001458 // Signal a refresh if a transaction modified the window state,
1459 // a new buffer was latched, or if HWC has requested a full
1460 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001461 signalRefresh();
1462 }
1463 break;
1464 }
1465 case MessageQueue::REFRESH: {
1466 handleMessageRefresh();
1467 break;
1468 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001469 }
1470}
1471
Dan Stoza6b9454d2014-11-07 16:00:59 -08001472bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001473 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001474 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001475 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001476 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001477 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001479}
1480
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001482 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001483 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001484}
1485
1486void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001487 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001488
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001489 mRefreshPending = false;
1490
Pablo Ceballos40845df2016-01-25 17:41:15 -08001491 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001492
Brian Andersond6927fb2016-07-23 23:37:30 -07001493 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001494 rebuildLayerStacks();
1495 setUpHWComposer();
1496 doDebugFlashRegions();
1497 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001498 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001499
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001500 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001501
1502 mHadClientComposition = false;
1503 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1504 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1505 mHadClientComposition = mHadClientComposition ||
1506 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1507 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001508
Dan Stoza9e56aa02015-11-02 13:00:03 -08001509 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001510}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001511
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512void SurfaceFlinger::doDebugFlashRegions()
1513{
1514 // is debugging enabled
1515 if (CC_LIKELY(!mDebugRegion))
1516 return;
1517
1518 const bool repaintEverything = mRepaintEverything;
1519 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1520 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001521 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001522 // transform the dirty region into this screen's coordinate space
1523 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1524 if (!dirtyRegion.isEmpty()) {
1525 // redraw the whole screen
1526 doComposeSurfaces(hw, Region(hw->bounds()));
1527
1528 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001529 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001530 RenderEngine& engine(getRenderEngine());
1531 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1532
Mathias Agopianda27af92012-09-13 18:17:13 -07001533 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001534 }
1535 }
1536 }
1537
1538 postFramebuffer();
1539
1540 if (mDebugRegion > 1) {
1541 usleep(mDebugRegion * 1000);
1542 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001543
Dan Stoza9e56aa02015-11-02 13:00:03 -08001544 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001545 auto& displayDevice = mDisplays[displayId];
1546 if (!displayDevice->isDisplayOn()) {
1547 continue;
1548 }
1549
1550 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001551 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1552 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001553 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001554}
1555
Brian Andersond6927fb2016-07-23 23:37:30 -07001556void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001558 ATRACE_CALL();
1559 ALOGV("preComposition");
1560
Mathias Agopiancd60f992012-08-16 16:28:27 -07001561 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001562 mDrawingState.traverseInZOrder([&](Layer* layer) {
1563 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001564 needExtraInvalidate = true;
1565 }
Robert Carr2047fae2016-11-28 14:09:09 -08001566 });
1567
Mathias Agopiancd60f992012-08-16 16:28:27 -07001568 if (needExtraInvalidate) {
1569 signalLayerUpdate();
1570 }
1571}
1572
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001573void SurfaceFlinger::updateCompositorTiming(
1574 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1575 std::shared_ptr<FenceTime>& presentFenceTime) {
1576 // Update queue of past composite+present times and determine the
1577 // most recently known composite to present latency.
1578 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1579 nsecs_t compositeToPresentLatency = -1;
1580 while (!mCompositePresentTimes.empty()) {
1581 CompositePresentTime& cpt = mCompositePresentTimes.front();
1582 // Cached values should have been updated before calling this method,
1583 // which helps avoid duplicate syscalls.
1584 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1585 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1586 break;
1587 }
1588 compositeToPresentLatency = displayTime - cpt.composite;
1589 mCompositePresentTimes.pop();
1590 }
1591
1592 // Don't let mCompositePresentTimes grow unbounded, just in case.
1593 while (mCompositePresentTimes.size() > 16) {
1594 mCompositePresentTimes.pop();
1595 }
1596
Brian Andersond0010582017-03-07 13:20:31 -08001597 setCompositorTimingSnapped(
1598 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1599}
1600
1601void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1602 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001603 // Integer division and modulo round toward 0 not -inf, so we need to
1604 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001605 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001606 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1607 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1608
Brian Andersond0010582017-03-07 13:20:31 -08001609 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1610 if (idealLatency <= 0) {
1611 idealLatency = vsyncInterval;
1612 }
1613
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001614 // Snap the latency to a value that removes scheduling jitter from the
1615 // composition and present times, which often have >1ms of jitter.
1616 // Reducing jitter is important if an app attempts to extrapolate
1617 // something (such as user input) to an accurate diasplay time.
1618 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1619 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001620 nsecs_t bias = vsyncInterval / 2;
1621 int64_t extraVsyncs =
1622 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1623 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1624 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001625
Brian Andersond0010582017-03-07 13:20:31 -08001626 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001627 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1628 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001629 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001630}
1631
1632void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001633{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001634 ATRACE_CALL();
1635 ALOGV("postComposition");
1636
Brian Anderson3546a3f2016-07-14 11:51:14 -07001637 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001638 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001639 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001640 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001641 }
1642
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001643 // |mStateLock| not needed as we are on the main thread
1644 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001645
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001646 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001647 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1648 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1649 glCompositionDoneFenceTime =
1650 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1651 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1652 } else {
1653 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1654 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001655
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001656 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001657 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1658 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1659 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001660
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001661 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1662 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1663
1664 // We use the refreshStartTime which might be sampled a little later than
1665 // when we started doing work for this frame, but that should be okay
1666 // since updateCompositorTiming has snapping logic.
1667 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001668 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001669 CompositorTiming compositorTiming;
1670 {
1671 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1672 compositorTiming = mCompositorTiming;
1673 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001674
Robert Carr2047fae2016-11-28 14:09:09 -08001675 mDrawingState.traverseInZOrder([&](Layer* layer) {
1676 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001677 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001678 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001679 recordBufferingStats(layer->getName().string(),
1680 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001681 }
Robert Carr2047fae2016-11-28 14:09:09 -08001682 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001683
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001684 if (presentFenceTime->isValid()) {
1685 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001686 enableHardwareVsync();
1687 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001688 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001689 }
1690 }
1691
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001692 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001693 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001694 enableHardwareVsync();
1695 }
1696 }
1697
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001698 if (mAnimCompositionPending) {
1699 mAnimCompositionPending = false;
1700
Brian Anderson4e606e32017-03-16 15:34:57 -07001701 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001702 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001703 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001704 } else {
1705 // The HWC doesn't support present fences, so use the refresh
1706 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001707 nsecs_t presentTime =
1708 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001709 mAnimFrameTracker.setActualPresentTime(presentTime);
1710 }
1711 mAnimFrameTracker.advanceFrame();
1712 }
Dan Stozab90cf072015-03-05 11:05:59 -08001713
1714 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1715 return;
1716 }
1717
1718 nsecs_t currentTime = systemTime();
1719 if (mHasPoweredOff) {
1720 mHasPoweredOff = false;
1721 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001722 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001723 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001724 if (numPeriods < NUM_BUCKETS - 1) {
1725 mFrameBuckets[numPeriods] += elapsedTime;
1726 } else {
1727 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1728 }
1729 mTotalTime += elapsedTime;
1730 }
1731 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001732}
1733
1734void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001735 ATRACE_CALL();
1736 ALOGV("rebuildLayerStacks");
1737
Mathias Agopiancd60f992012-08-16 16:28:27 -07001738 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001739 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1740 ATRACE_CALL();
1741 mVisibleRegionsDirty = false;
1742 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001743
Jeff Sharkey76488112017-02-27 14:15:18 -07001744 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1745 Region opaqueRegion;
1746 Region dirtyRegion;
1747 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001748 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001749 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1750 const Transform& tr(displayDevice->getTransform());
1751 const Rect bounds(displayDevice->getBounds());
1752 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001753 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001754
Jeff Sharkey76488112017-02-27 14:15:18 -07001755 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001756 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001757 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1758 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001759 Region drawRegion(tr.transform(
1760 layer->visibleNonTransparentRegion));
1761 drawRegion.andSelf(bounds);
1762 if (!drawRegion.isEmpty()) {
1763 layersSortedByZ.add(layer);
1764 } else {
1765 // Clear out the HWC layer if this layer was
1766 // previously visible, but no longer is
Chia-I Wu92257612017-11-20 10:43:41 -08001767 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001768 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001769 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001770 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001771 // WM changes displayDevice->layerStack upon sleep/awake.
1772 // Here we make sure we delete the HWC layers even if
1773 // WM changed their layer stack.
Chia-I Wu92257612017-11-20 10:43:41 -08001774 hwcLayerDestroyed = layer->destroyHwcLayer(
1775 displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001776 }
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001777
1778 // If a layer is not going to get a release fence because
1779 // it is invisible, but it is also going to release its
1780 // old buffer, add it to the list of layers needing
1781 // fences.
1782 if (hwcLayerDestroyed) {
1783 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1784 mLayersWithQueuedFrames.cend(), layer);
1785 if (found != mLayersWithQueuedFrames.cend()) {
1786 layersNeedingFences.add(layer);
1787 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001788 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001789 });
1790 }
1791 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001792 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001793 displayDevice->undefinedRegion.set(bounds);
1794 displayDevice->undefinedRegion.subtractSelf(
1795 tr.transform(opaqueRegion));
1796 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001797 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001798 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001799}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001800
Romain Guy0147a172017-06-01 13:53:56 -07001801mat4 SurfaceFlinger::computeSaturationMatrix() const {
1802 if (mSaturation == 1.0f) {
1803 return mat4();
1804 }
1805
1806 // Rec.709 luma coefficients
1807 float3 luminance{0.213f, 0.715f, 0.072f};
1808 luminance *= 1.0f - mSaturation;
1809 return mat4(
1810 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1811 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1812 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1813 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1814 );
1815}
1816
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001817// pickColorMode translates a given dataspace into the best available color mode.
1818// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001819android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001820 switch (dataSpace) {
1821 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1822 // system expects.
1823 case HAL_DATASPACE_UNKNOWN:
1824 case HAL_DATASPACE_SRGB:
1825 case HAL_DATASPACE_V0_SRGB:
1826 return HAL_COLOR_MODE_SRGB;
1827 break;
1828
1829 case HAL_DATASPACE_DISPLAY_P3:
1830 return HAL_COLOR_MODE_DISPLAY_P3;
1831 break;
1832
1833 default:
1834 // TODO (courtneygo): Do we want to assert an error here?
1835 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1836 dataSpace);
1837 return HAL_COLOR_MODE_SRGB;
1838 break;
1839 }
1840}
1841
Romain Guy0147a172017-06-01 13:53:56 -07001842android_dataspace SurfaceFlinger::bestTargetDataSpace(
1843 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001844 // Only support sRGB and Display-P3 right now.
1845 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1846 return HAL_DATASPACE_DISPLAY_P3;
1847 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001848 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1849 return HAL_DATASPACE_DISPLAY_P3;
1850 }
1851 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1852 return HAL_DATASPACE_DISPLAY_P3;
1853 }
1854
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001855 return HAL_DATASPACE_V0_SRGB;
1856}
1857
Mathias Agopiancd60f992012-08-16 16:28:27 -07001858void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001859 ATRACE_CALL();
1860 ALOGV("setUpHWComposer");
1861
Jesse Hall028dc8f2013-08-20 16:35:32 -07001862 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001863 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1864 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1865 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1866
1867 // If nothing has changed (!dirty), don't recompose.
1868 // If something changed, but we don't currently have any visible layers,
1869 // and didn't when we last did a composition, then skip it this time.
1870 // The second rule does two things:
1871 // - When all layers are removed from a display, we'll emit one black
1872 // frame, then nothing more until we get new layers.
1873 // - When a display is created with a private layer stack, we won't
1874 // emit any black frames until a layer is added to the layer stack.
1875 bool mustRecompose = dirty && !(empty && wasEmpty);
1876
1877 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1878 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1879 mustRecompose ? "doing" : "skipping",
1880 dirty ? "+" : "-",
1881 empty ? "+" : "-",
1882 wasEmpty ? "+" : "-");
1883
Dan Stoza71433162014-02-04 16:22:36 -08001884 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001885
1886 if (mustRecompose) {
1887 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1888 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001889 }
1890
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 // build the h/w work list
1892 if (CC_UNLIKELY(mGeometryInvalid)) {
1893 mGeometryInvalid = false;
1894 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1895 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1896 const auto hwcId = displayDevice->getHwcDisplayId();
1897 if (hwcId >= 0) {
1898 const Vector<sp<Layer>>& currentLayers(
1899 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001900 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001901 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001902 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001903 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001904 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001905 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001906 }
1907 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001908
Robert Carrae060832016-11-28 10:51:00 -08001909 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001910 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001911 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001912 }
1913 }
1914 }
1915 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001916 }
Riley Andrews03414a12014-07-01 14:22:59 -07001917
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001918
Romain Guy0147a172017-06-01 13:53:56 -07001919 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001920
Dan Stoza9e56aa02015-11-02 13:00:03 -08001921 // Set the per-frame data
1922 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1923 auto& displayDevice = mDisplays[displayId];
1924 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001925
Dan Stoza9e56aa02015-11-02 13:00:03 -08001926 if (hwcId < 0) {
1927 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001928 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001929 if (colorMatrix != mPreviousColorMatrix) {
1930 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1931 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1932 "display %zd: %d", displayId, result);
1933 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1935 layer->setPerFrameData(displayDevice);
1936 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001937
1938 if (hasWideColorDisplay) {
1939 android_color_mode newColorMode;
1940 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1941
1942 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1943 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1944 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1945 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1946 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1947 }
1948 newColorMode = pickColorMode(newDataSpace);
1949
Thierry Strudel2924d012017-08-14 15:19:37 -07001950 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001951 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001952 }
1953
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001954 mPreviousColorMatrix = colorMatrix;
1955
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001957 auto& displayDevice = mDisplays[displayId];
1958 if (!displayDevice->isDisplayOn()) {
1959 continue;
1960 }
1961
1962 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001963 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1964 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001965 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001966}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001967
Mathias Agopiancd60f992012-08-16 16:28:27 -07001968void SurfaceFlinger::doComposition() {
1969 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001970 ALOGV("doComposition");
1971
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001972 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001973 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001974 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001975 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001976 // transform the dirty region into this screen's coordinate space
1977 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001978
1979 // repaint the framebuffer (if needed)
1980 doDisplayComposition(hw, dirtyRegion);
1981
Mathias Agopiancd60f992012-08-16 16:28:27 -07001982 hw->dirtyRegion.clear();
1983 hw->flip(hw->swapRegion);
1984 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001985 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001986 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001987 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001988}
1989
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001990void SurfaceFlinger::postFramebuffer()
1991{
Mathias Agopian841cde52012-03-01 15:44:37 -08001992 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001993 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001994
Mathias Agopiana44b0412011-10-16 18:46:35 -07001995 const nsecs_t now = systemTime();
1996 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001997
Dan Stoza9e56aa02015-11-02 13:00:03 -08001998 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1999 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002000 if (!displayDevice->isDisplayOn()) {
2001 continue;
2002 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 const auto hwcId = displayDevice->getHwcDisplayId();
2004 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002005 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002006 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002007 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002008 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002009 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002010 // The layer buffer from the previous frame (if any) is released
2011 // by HWC only when the release fence from this frame (if any) is
2012 // signaled. Always get the release fence from HWC first.
2013 auto hwcLayer = layer->getHwcLayer(hwcId);
2014 sp<Fence> releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2015
2016 // If the layer was client composited in the previous frame, we
2017 // need to merge with the previous client target acquire fence.
2018 // Since we do not track that, always merge with the current
2019 // client target acquire fence when it is available, even though
2020 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002021 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002022 releaseFence = Fence::merge("LayerRelease", releaseFence,
2023 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002024 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002025
Dan Stoza9e56aa02015-11-02 13:00:03 -08002026 layer->onLayerDisplayed(releaseFence);
2027 }
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08002028
2029 // We've got a list of layers needing fences, that are disjoint with
2030 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2031 // supply them with the present fence.
2032 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
2033 sp<Fence> presentFence = mHwc->getPresentFence(hwcId);
2034 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2035 layer->onLayerDisplayed(presentFence);
2036 }
2037 }
2038
Dan Stoza9e56aa02015-11-02 13:00:03 -08002039 if (hwcId >= 0) {
2040 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002041 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002042 }
2043
Mathias Agopiana44b0412011-10-16 18:46:35 -07002044 mLastSwapBufferTime = systemTime() - now;
2045 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002046
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002047 // |mStateLock| not needed as we are on the main thread
2048 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002049 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2050 logFrameStats();
2051 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002052}
2053
Mathias Agopian87baae12012-07-31 12:38:26 -07002054void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002055{
Mathias Agopian841cde52012-03-01 15:44:37 -08002056 ATRACE_CALL();
2057
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002058 // here we keep a copy of the drawing state (that is the state that's
2059 // going to be overwritten by handleTransactionLocked()) outside of
2060 // mStateLock so that the side-effects of the State assignment
2061 // don't happen with mStateLock held (which can cause deadlocks).
2062 State drawingState(mDrawingState);
2063
Mathias Agopianca4d3602011-05-19 15:38:14 -07002064 Mutex::Autolock _l(mStateLock);
2065 const nsecs_t now = systemTime();
2066 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002067
Mathias Agopianca4d3602011-05-19 15:38:14 -07002068 // Here we're guaranteed that some transaction flags are set
2069 // so we can call handleTransactionLocked() unconditionally.
2070 // We call getTransactionFlags(), which will also clear the flags,
2071 // with mStateLock held to guarantee that mCurrentState won't change
2072 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002073
Mathias Agopiane57f2922012-08-09 16:29:12 -07002074 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002075 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002076
Mathias Agopianca4d3602011-05-19 15:38:14 -07002077 mLastTransactionTime = systemTime() - now;
2078 mDebugInTransaction = 0;
2079 invalidateHwcGeometry();
2080 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002081}
2082
Lloyd Pique3e3d28c2017-12-14 17:11:26 -08002083void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2084 for (const auto& event : mPendingHotplugEvents) {
2085 DisplayDevice::DisplayType displayType = event.isPrimaryDisplay
2086 ? DisplayDevice::DISPLAY_PRIMARY
2087 : DisplayDevice::DISPLAY_EXTERNAL;
2088
2089 if (mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2090 ALOGE("External displays are not supported by the vr hardware composer.");
2091 continue;
2092 }
2093
2094 mHwc->onHotplug(event.display, event.connection);
2095
2096 if (event.connection == HWC2::Connection::Connected) {
2097 createBuiltinDisplayLocked(displayType);
2098 } else {
2099 mCurrentState.displays.removeItem(mBuiltinDisplays[displayType]);
2100 mBuiltinDisplays[displayType].clear();
2101 }
2102
2103 if (displayType == DisplayDevice::DISPLAY_PRIMARY) {
2104 createDefaultDisplayDevice();
2105 }
2106
2107 processDisplayChangesLocked();
2108 }
2109
2110 mPendingHotplugEvents.clear();
2111}
2112
Lloyd Piqueb3206282017-12-14 17:00:15 -08002113void SurfaceFlinger::processDisplayChangesLocked() {
2114 // here we take advantage of Vector's copy-on-write semantics to
2115 // improve performance by skipping the transaction entirely when
2116 // know that the lists are identical
2117 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2118 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2119 if (!curr.isIdenticalTo(draw)) {
2120 mVisibleRegionsDirty = true;
2121 const size_t cc = curr.size();
2122 size_t dc = draw.size();
2123
2124 // find the displays that were removed
2125 // (ie: in drawing state but not in current state)
2126 // also handle displays that changed
2127 // (ie: displays that are in both lists)
2128 for (size_t i = 0; i < dc;) {
2129 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2130 if (j < 0) {
2131 // in drawing state but not in current state
2132 if (!draw[i].isMainDisplay()) {
2133 // Call makeCurrent() on the primary display so we can
2134 // be sure that nothing associated with this display
2135 // is current.
2136 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2137 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
2138 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2139 if (hw != NULL) hw->disconnect(getHwComposer());
2140 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2141 mEventThread->onHotplugReceived(draw[i].type, false);
2142 mDisplays.removeItem(draw.keyAt(i));
2143 } else {
2144 ALOGW("trying to remove the main display");
2145 }
2146 } else {
2147 // this display is in both lists. see if something changed.
2148 const DisplayDeviceState& state(curr[j]);
2149 const wp<IBinder>& display(curr.keyAt(j));
2150 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2151 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2152 if (state_binder != draw_binder) {
2153 // changing the surface is like destroying and
2154 // recreating the DisplayDevice, so we just remove it
2155 // from the drawing state, so that it get re-added
2156 // below.
2157 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2158 if (hw != NULL) hw->disconnect(getHwComposer());
2159 mDisplays.removeItem(display);
2160 mDrawingState.displays.removeItemsAt(i);
2161 dc--;
2162 // at this point we must loop to the next item
2163 continue;
2164 }
2165
2166 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2167 if (disp != NULL) {
2168 if (state.layerStack != draw[i].layerStack) {
2169 disp->setLayerStack(state.layerStack);
2170 }
2171 if ((state.orientation != draw[i].orientation) ||
2172 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2173 disp->setProjection(state.orientation, state.viewport, state.frame);
2174 }
2175 if (state.width != draw[i].width || state.height != draw[i].height) {
2176 disp->setDisplaySize(state.width, state.height);
2177 }
2178 }
2179 }
2180 ++i;
2181 }
2182
2183 // find displays that were added
2184 // (ie: in current state but not in drawing state)
2185 for (size_t i = 0; i < cc; i++) {
2186 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2187 const DisplayDeviceState& state(curr[i]);
2188
2189 sp<DisplaySurface> dispSurface;
2190 sp<IGraphicBufferProducer> producer;
2191 sp<IGraphicBufferProducer> bqProducer;
2192 sp<IGraphicBufferConsumer> bqConsumer;
2193 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
2194
2195 int32_t hwcId = -1;
2196 if (state.isVirtualDisplay()) {
2197 // Virtual displays without a surface are dormant:
2198 // they have external state (layer stack, projection,
2199 // etc.) but no internal state (i.e. a DisplayDevice).
2200 if (state.surface != NULL) {
2201 // Allow VR composer to use virtual displays.
2202 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
2203 int width = 0;
2204 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2205 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2206 int height = 0;
2207 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2208 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2209 int intFormat = 0;
2210 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2211 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2212 auto format = static_cast<android_pixel_format_t>(intFormat);
2213
2214 mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2215 }
2216
2217 // TODO: Plumb requested format back up to consumer
2218
2219 sp<VirtualDisplaySurface> vds =
2220 new VirtualDisplaySurface(*mHwc, hwcId, state.surface, bqProducer,
2221 bqConsumer, state.displayName);
2222
2223 dispSurface = vds;
2224 producer = vds;
2225 }
2226 } else {
2227 ALOGE_IF(state.surface != NULL,
2228 "adding a supported display, but rendering "
2229 "surface is provided (%p), ignoring it",
2230 state.surface.get());
2231
2232 hwcId = state.type;
2233 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2234 producer = bqProducer;
2235 }
2236
2237 const wp<IBinder>& display(curr.keyAt(i));
2238 if (dispSurface != NULL) {
2239 sp<DisplayDevice> hw =
2240 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2241 dispSurface, producer, mRenderEngine->getEGLConfig(),
2242 hasWideColorDisplay);
2243 hw->setLayerStack(state.layerStack);
2244 hw->setProjection(state.orientation, state.viewport, state.frame);
2245 hw->setDisplayName(state.displayName);
2246 mDisplays.add(display, hw);
2247 if (!state.isVirtualDisplay()) {
2248 mEventThread->onHotplugReceived(state.type, true);
2249 }
2250 }
2251 }
2252 }
2253 }
Lloyd Pique3e3d28c2017-12-14 17:11:26 -08002254
2255 mDrawingState.displays = mCurrentState.displays;
Lloyd Piqueb3206282017-12-14 17:00:15 -08002256}
2257
Mathias Agopian87baae12012-07-31 12:38:26 -07002258void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002259{
Dan Stoza7dde5992015-05-22 09:51:44 -07002260 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002261 mCurrentState.traverseInZOrder([](Layer* layer) {
2262 layer->notifyAvailableFrames();
2263 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002264
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002265 /*
2266 * Traversal of the children
2267 * (perform the transaction for each of them if needed)
2268 */
2269
Mathias Agopian3559b072012-08-15 13:46:03 -07002270 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002271 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002272 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002273 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002274
2275 const uint32_t flags = layer->doTransaction(0);
2276 if (flags & Layer::eVisibleRegion)
2277 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002278 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002279 }
2280
2281 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002282 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002283 */
2284
Mathias Agopiane57f2922012-08-09 16:29:12 -07002285 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Piqueb3206282017-12-14 17:00:15 -08002286 processDisplayChangesLocked();
Lloyd Pique3e3d28c2017-12-14 17:11:26 -08002287 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002288 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002289
Mathias Agopian84300952012-11-21 16:02:13 -08002290 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2291 // The transform hint might have changed for some layers
2292 // (either because a display has changed, or because a layer
2293 // as changed).
2294 //
2295 // Walk through all the layers in currentLayers,
2296 // and update their transform hint.
2297 //
2298 // If a layer is visible only on a single display, then that
2299 // display is used to calculate the hint, otherwise we use the
2300 // default display.
2301 //
2302 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2303 // the hint is set before we acquire a buffer from the surface texture.
2304 //
2305 // NOTE: layer transactions have taken place already, so we use their
2306 // drawing state. However, SurfaceFlinger's own transaction has not
2307 // happened yet, so we must use the current state layer list
2308 // (soon to become the drawing state list).
2309 //
2310 sp<const DisplayDevice> disp;
2311 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002312 bool first = true;
2313 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002314 // NOTE: we rely on the fact that layers are sorted by
2315 // layerStack first (so we don't have to traverse the list
2316 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002317 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002318 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002319 currentlayerStack = layerStack;
2320 // figure out if this layerstack is mirrored
2321 // (more than one display) if so, pick the default display,
2322 // if not, pick the only display it's on.
2323 disp.clear();
2324 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2325 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002326 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002327 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002328 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002329 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002330 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002331 break;
2332 }
2333 }
2334 }
2335 }
Chet Haase91d25932013-04-11 15:24:55 -07002336 if (disp == NULL) {
2337 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2338 // redraw after transform hint changes. See bug 8508397.
2339
2340 // could be null when this layer is using a layerStack
2341 // that is not visible on any display. Also can occur at
2342 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002343 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002344 }
Chet Haase91d25932013-04-11 15:24:55 -07002345 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002346
2347 first = false;
2348 });
Mathias Agopian84300952012-11-21 16:02:13 -08002349 }
2350
2351
Mathias Agopian3559b072012-08-15 13:46:03 -07002352 /*
2353 * Perform our own transaction if needed
2354 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002355
2356 if (mLayersAdded) {
2357 mLayersAdded = false;
2358 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002359 mVisibleRegionsDirty = true;
2360 }
2361
2362 // some layers might have been removed, so
2363 // we need to update the regions they're exposing.
2364 if (mLayersRemoved) {
2365 mLayersRemoved = false;
2366 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002367 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002368 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002369 // this layer is not visible anymore
2370 // TODO: we could traverse the tree from front to back and
2371 // compute the actual visible region
2372 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002373 Region visibleReg;
2374 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002375 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002376 }
Robert Carr2047fae2016-11-28 14:09:09 -08002377 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002378 }
2379
2380 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002381
2382 updateCursorAsync();
2383}
2384
2385void SurfaceFlinger::updateCursorAsync()
2386{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002387 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2388 auto& displayDevice = mDisplays[displayId];
2389 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002390 continue;
2391 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002392
2393 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2394 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002395 }
2396 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002397}
2398
2399void SurfaceFlinger::commitTransaction()
2400{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002401 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002402 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002403 for (const auto& l : mLayersPendingRemoval) {
2404 recordBufferingStats(l->getName().string(),
2405 l->getOccupancyHistory(true));
2406 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002407 }
2408 mLayersPendingRemoval.clear();
2409 }
2410
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002411 // If this transaction is part of a window animation then the next frame
2412 // we composite should be considered an animation as well.
2413 mAnimCompositionPending = mAnimTransactionPending;
2414
Mathias Agopian4fec8732012-06-29 14:12:52 -07002415 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002416 mDrawingState.traverseInZOrder([](Layer* layer) {
2417 layer->commitChildList();
2418 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002419 mTransactionPending = false;
2420 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002421 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002422}
2423
Chia-I Wuab0c3192017-08-01 11:29:00 -07002424void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002425 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002426{
Mathias Agopian841cde52012-03-01 15:44:37 -08002427 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002428 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002429
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002430 Region aboveOpaqueLayers;
2431 Region aboveCoveredLayers;
2432 Region dirty;
2433
Mathias Agopian87baae12012-07-31 12:38:26 -07002434 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002435
Robert Carr2047fae2016-11-28 14:09:09 -08002436 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002437 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002438 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439
Jesse Hall01e29052013-02-19 16:13:35 -08002440 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002441 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002442 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002443
Mathias Agopianab028732010-03-16 16:41:46 -07002444 /*
2445 * opaqueRegion: area of a surface that is fully opaque.
2446 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002447 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002448
2449 /*
2450 * visibleRegion: area of a surface that is visible on screen
2451 * and not fully transparent. This is essentially the layer's
2452 * footprint minus the opaque regions above it.
2453 * Areas covered by a translucent surface are considered visible.
2454 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002456
2457 /*
2458 * coveredRegion: area of a surface that is covered by all
2459 * visible regions above it (which includes the translucent areas).
2460 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002461 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002462
Jesse Halla8026d22012-09-25 13:25:04 -07002463 /*
2464 * transparentRegion: area of a surface that is hinted to be completely
2465 * transparent. This is only used to tell when the layer has no visible
2466 * non-transparent regions and can be removed from the layer list. It
2467 * does not affect the visibleRegion of this layer or any layers
2468 * beneath it. The hint may not be correct if apps don't respect the
2469 * SurfaceView restrictions (which, sadly, some don't).
2470 */
2471 Region transparentRegion;
2472
Mathias Agopianab028732010-03-16 16:41:46 -07002473
2474 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002475 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002476 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002477 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002478 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002479 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002480 if (!visibleRegion.isEmpty()) {
2481 // Remove the transparent area from the visible region
2482 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002483 if (tr.preserveRects()) {
2484 // transform the transparent region
2485 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002486 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002487 // transformation too complex, can't do the
2488 // transparent region optimization.
2489 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002490 }
Mathias Agopianab028732010-03-16 16:41:46 -07002491 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492
Mathias Agopianab028732010-03-16 16:41:46 -07002493 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002494 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002495 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002496 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2497 // the opaque region is the layer's footprint
2498 opaqueRegion = visibleRegion;
2499 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500 }
2501 }
2502
Mathias Agopianab028732010-03-16 16:41:46 -07002503 // Clip the covered region to the visible region
2504 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2505
2506 // Update aboveCoveredLayers for next (lower) layer
2507 aboveCoveredLayers.orSelf(visibleRegion);
2508
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509 // subtract the opaque region covered by the layers above us
2510 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511
2512 // compute this layer's dirty region
2513 if (layer->contentDirty) {
2514 // we need to invalidate the whole region
2515 dirty = visibleRegion;
2516 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002517 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518 layer->contentDirty = false;
2519 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002520 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002521 * the exposed region consists of two components:
2522 * 1) what's VISIBLE now and was COVERED before
2523 * 2) what's EXPOSED now less what was EXPOSED before
2524 *
2525 * note that (1) is conservative, we start with the whole
2526 * visible region but only keep what used to be covered by
2527 * something -- which mean it may have been exposed.
2528 *
2529 * (2) handles areas that were not covered by anything but got
2530 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002531 */
Mathias Agopianab028732010-03-16 16:41:46 -07002532 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002533 const Region oldVisibleRegion = layer->visibleRegion;
2534 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002535 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2536 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002537 }
2538 dirty.subtractSelf(aboveOpaqueLayers);
2539
2540 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002541 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002542
Mathias Agopianab028732010-03-16 16:41:46 -07002543 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002544 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002545
Jesse Halla8026d22012-09-25 13:25:04 -07002546 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547 layer->setVisibleRegion(visibleRegion);
2548 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002549 layer->setVisibleNonTransparentRegion(
2550 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002551 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552
Mathias Agopian87baae12012-07-31 12:38:26 -07002553 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554}
2555
Chia-I Wuab0c3192017-08-01 11:29:00 -07002556void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002557 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002558 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002559 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002560 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002561 }
2562 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002563}
2564
Dan Stoza6b9454d2014-11-07 16:00:59 -08002565bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002566{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002567 ALOGV("handlePageFlip");
2568
Brian Andersond6927fb2016-07-23 23:37:30 -07002569 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002570
Mathias Agopian4fec8732012-06-29 14:12:52 -07002571 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002572 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002573 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002574
2575 // Store the set of layers that need updates. This set must not change as
2576 // buffers are being latched, as this could result in a deadlock.
2577 // Example: Two producers share the same command stream and:
2578 // 1.) Layer 0 is latched
2579 // 2.) Layer 0 gets a new frame
2580 // 2.) Layer 1 gets a new frame
2581 // 3.) Layer 1 is latched.
2582 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2583 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002584 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002585 if (layer->hasQueuedFrame()) {
2586 frameQueued = true;
2587 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002588 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002589 } else {
2590 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002591 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002592 } else {
2593 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002594 }
Robert Carr2047fae2016-11-28 14:09:09 -08002595 });
2596
Dan Stoza9e56aa02015-11-02 13:00:03 -08002597 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002598 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002599 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002600 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002601 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002602 newDataLatched = true;
2603 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002604 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002605
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002606 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002607
2608 // If we will need to wake up at some time in the future to deal with a
2609 // queued frame that shouldn't be displayed during this vsync period, wake
2610 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002611 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002612 signalLayerUpdate();
2613 }
2614
2615 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002616 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002617}
2618
Mathias Agopianad456f92011-01-13 17:53:01 -08002619void SurfaceFlinger::invalidateHwcGeometry()
2620{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002621 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002622}
2623
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002624
Fabien Sanglard830b8472016-11-30 16:35:58 -08002625void SurfaceFlinger::doDisplayComposition(
2626 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002627 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628{
Dan Stoza71433162014-02-04 16:22:36 -08002629 // We only need to actually compose the display if:
2630 // 1) It is being handled by hardware composer, which may need this to
2631 // keep its virtual display state machine in sync, or
2632 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002633 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002634 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002635 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002636 return;
2637 }
2638
Dan Stoza9e56aa02015-11-02 13:00:03 -08002639 ALOGV("doDisplayComposition");
2640
Mathias Agopian87baae12012-07-31 12:38:26 -07002641 Region dirtyRegion(inDirtyRegion);
2642
Mathias Agopianb8a55602009-06-26 19:06:36 -07002643 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002644 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645
Fabien Sanglard830b8472016-11-30 16:35:58 -08002646 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002647 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002648 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2649 // takes a rectangle, we must make sure to update that whole
2650 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002651 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002652 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002653 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002654 // We need to redraw the rectangle that will be updated
2655 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002656 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002657 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002658 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002659 } else {
2660 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002661 dirtyRegion.set(displayDevice->bounds());
2662 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 }
2664 }
2665
Fabien Sanglard830b8472016-11-30 16:35:58 -08002666 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002668 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002669 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002670
2671 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002672 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673}
2674
Dan Stoza9e56aa02015-11-02 13:00:03 -08002675bool SurfaceFlinger::doComposeSurfaces(
2676 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002677{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002678 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002679
Dan Stoza9e56aa02015-11-02 13:00:03 -08002680 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002681
2682 mat4 oldColorMatrix;
2683 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2684 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2685 if (applyColorMatrix) {
2686 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2687 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2688 }
2689
Dan Stoza9e56aa02015-11-02 13:00:03 -08002690 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2691 if (hasClientComposition) {
2692 ALOGV("hasClientComposition");
2693
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002694#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002695 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002696 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002697#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002698 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002699 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002700 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002701 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002702
2703 // |mStateLock| not needed as we are on the main thread
2704 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002705 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2706 }
2707 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002708 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002709
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002710 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002711 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2712 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002713 // when using overlays, we assume a fully transparent framebuffer
2714 // NOTE: we could reduce how much we need to clear, for instance
2715 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002716 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002717 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002718 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002719 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002720 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002721 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002722
2723 // we remove the scissor part
2724 // we're left with the letterbox region
2725 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002726 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002727
2728 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002729 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002730
2731 // but limit it to the dirty region
2732 region.andSelf(dirty);
2733
Mathias Agopianb9494d52012-04-18 02:28:45 -07002734 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002735 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002736 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002737 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002738 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002739 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002740
Dan Stoza9e56aa02015-11-02 13:00:03 -08002741 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002742 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002743 // scissor on the main display. It should never be needed
2744 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002745 const Rect& bounds(displayDevice->getBounds());
2746 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002747 if (scissor != bounds) {
2748 // scissor doesn't match the screen's dimensions, so we
2749 // need to clear everything outside of it and enable
2750 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002751
Mathias Agopianf45c5102012-10-24 16:29:17 -07002752 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002753 const uint32_t height = displayDevice->getHeight();
2754 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002755 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002756 }
2757 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002758 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002759
Mathias Agopian85d751c2012-08-29 16:59:24 -07002760 /*
2761 * and then, render the layers targeted at the framebuffer
2762 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002763
Dan Stoza9e56aa02015-11-02 13:00:03 -08002764 ALOGV("Rendering client layers");
2765 const Transform& displayTransform = displayDevice->getTransform();
2766 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002767 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002768 bool firstLayer = true;
2769 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2770 const Region clip(dirty.intersect(
2771 displayTransform.transform(layer->visibleRegion)));
2772 ALOGV("Layer: %s", layer->getName().string());
2773 ALOGV(" Composition type: %s",
2774 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002775 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002776 switch (layer->getCompositionType(hwcId)) {
2777 case HWC2::Composition::Cursor:
2778 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002779 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002780 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002781 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002782 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2783 layer->isOpaque(state) && (state.alpha == 1.0f)
2784 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002785 // never clear the very first layer since we're
2786 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002787 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002788 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002789 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002790 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002791 case HWC2::Composition::Client: {
2792 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002793 break;
2794 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002795 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002796 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002797 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002798 } else {
2799 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002800 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002801 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002802 }
2803 } else {
2804 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002805 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002806 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002807 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002808 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002809 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002810 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002811 }
2812 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002813
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002814 if (applyColorMatrix) {
2815 getRenderEngine().setupColorTransform(oldColorMatrix);
2816 }
2817
Mathias Agopianf45c5102012-10-24 16:29:17 -07002818 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002819 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002820 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821}
2822
Fabien Sanglard830b8472016-11-30 16:35:58 -08002823void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2824 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002825 RenderEngine& engine(getRenderEngine());
2826 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827}
2828
Dan Stoza7d89d062015-04-30 13:29:25 -07002829status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002830 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002831 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002832 const sp<Layer>& lbc,
2833 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002834{
Dan Stoza7d89d062015-04-30 13:29:25 -07002835 // add this layer to the current state list
2836 {
2837 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002838 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002839 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2840 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002841 return NO_MEMORY;
2842 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002843 if (parent == nullptr) {
2844 mCurrentState.layersSortedByZ.add(lbc);
2845 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002846 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2847 ALOGE("addClientLayer called with a removed parent");
2848 return NAME_NOT_FOUND;
2849 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002850 parent->addChild(lbc);
2851 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002852
Dan Stoza7d89d062015-04-30 13:29:25 -07002853 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002854 mLayersAdded = true;
2855 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002856 }
2857
Mathias Agopian96f08192010-06-02 23:28:45 -07002858 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002859 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002860
Dan Stoza7d89d062015-04-30 13:29:25 -07002861 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002862}
2863
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002864status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002865 Mutex::Autolock _l(mStateLock);
2866
Robert Carr1f0a16a2016-10-24 16:27:39 -07002867 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002868 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002869 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002870 if (topLevelOnly) {
2871 return NO_ERROR;
2872 }
2873
Chia-I Wu98f1c102017-05-30 14:54:08 -07002874 sp<Layer> ancestor = p;
2875 while (ancestor->getParent() != nullptr) {
2876 ancestor = ancestor->getParent();
2877 }
2878 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2879 ALOGE("removeLayer called with a layer whose parent has been removed");
2880 return NAME_NOT_FOUND;
2881 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002882
2883 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002884 } else {
2885 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002886 }
2887
Robert Carr136e2f62017-02-08 17:54:29 -08002888 // As a matter of normal operation, the LayerCleaner will produce a second
2889 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2890 // so we will succeed in promoting it, but it's already been removed
2891 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2892 // otherwise something has gone wrong and we are leaking the layer.
2893 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002894 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2895 layer->getName().string(),
2896 (p != nullptr) ? p->getName().string() : "no-parent");
2897 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002898 } else if (index < 0) {
2899 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002900 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002901
Chia-I Wuc6657022017-08-15 11:18:17 -07002902 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002903 mLayersPendingRemoval.add(layer);
2904 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002905 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002906 setTransactionFlags(eTransactionNeeded);
2907 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908}
2909
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002910uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002911 return android_atomic_release_load(&mTransactionFlags);
2912}
2913
Mathias Agopian3f844832013-08-07 21:24:32 -07002914uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002915 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2916}
2917
Mathias Agopian3f844832013-08-07 21:24:32 -07002918uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002919 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2920 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002921 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922 }
2923 return old;
2924}
2925
Mathias Agopian8b33f032012-07-24 20:43:54 -07002926void SurfaceFlinger::setTransactionState(
2927 const Vector<ComposerState>& state,
2928 const Vector<DisplayState>& displays,
2929 uint32_t flags)
2930{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002931 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002932 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002933 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002934
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002935 if (flags & eAnimation) {
2936 // For window updates that are part of an animation we must wait for
2937 // previous animation "frames" to be handled.
2938 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002939 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002940 if (CC_UNLIKELY(err != NO_ERROR)) {
2941 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002942 // caller after a few seconds.
2943 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2944 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002945 mAnimTransactionPending = false;
2946 break;
2947 }
2948 }
2949 }
2950
Mathias Agopiane57f2922012-08-09 16:29:12 -07002951 size_t count = displays.size();
2952 for (size_t i=0 ; i<count ; i++) {
2953 const DisplayState& s(displays[i]);
2954 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002955 }
2956
Mathias Agopiane57f2922012-08-09 16:29:12 -07002957 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002958 for (size_t i=0 ; i<count ; i++) {
2959 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002960 // Here we need to check that the interface we're given is indeed
2961 // one of our own. A malicious client could give us a NULL
2962 // IInterface, or one of its own or even one of our own but a
2963 // different type. All these situations would cause us to crash.
2964 //
2965 // NOTE: it would be better to use RTTI as we could directly check
2966 // that we have a Client*. however, RTTI is disabled in Android.
2967 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002968 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002969 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002970 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002971 sp<Client> client( static_cast<Client *>(s.client.get()) );
2972 transactionFlags |= setClientStateLocked(client, s.state);
2973 }
2974 }
2975 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002976 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002977
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002978 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2979 // anyway. This can be used as a flush mechanism for previous async transactions.
2980 // Empty animation transaction can be used to simulate back-pressure, so also force a
2981 // transaction for empty animation transactions.
2982 if (transactionFlags == 0 &&
2983 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002984 transactionFlags = eTransactionNeeded;
2985 }
2986
Mathias Agopian386aa982011-11-07 21:58:03 -08002987 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002988 if (mInterceptor.isEnabled()) {
2989 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2990 }
Irvel468051e2016-06-13 16:44:44 -07002991
Mathias Agopian386aa982011-11-07 21:58:03 -08002992 // this triggers the transaction
2993 setTransactionFlags(transactionFlags);
2994
2995 // if this is a synchronous transaction, wait for it to take effect
2996 // before returning.
2997 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002998 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002999 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003000 if (flags & eAnimation) {
3001 mAnimTransactionPending = true;
3002 }
3003 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003004 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3005 if (CC_UNLIKELY(err != NO_ERROR)) {
3006 // just in case something goes wrong in SF, return to the
3007 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003008 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3009 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003010 break;
3011 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003012 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003013 }
3014}
3015
Mathias Agopiane57f2922012-08-09 16:29:12 -07003016uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3017{
Jesse Hall9a143922012-10-04 16:29:19 -07003018 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3019 if (dpyIdx < 0)
3020 return 0;
3021
Mathias Agopiane57f2922012-08-09 16:29:12 -07003022 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003023 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003024 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003025 const uint32_t what = s.what;
3026 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003027 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003028 disp.surface = s.surface;
3029 flags |= eDisplayTransactionNeeded;
3030 }
3031 }
3032 if (what & DisplayState::eLayerStackChanged) {
3033 if (disp.layerStack != s.layerStack) {
3034 disp.layerStack = s.layerStack;
3035 flags |= eDisplayTransactionNeeded;
3036 }
3037 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003038 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003039 if (disp.orientation != s.orientation) {
3040 disp.orientation = s.orientation;
3041 flags |= eDisplayTransactionNeeded;
3042 }
3043 if (disp.frame != s.frame) {
3044 disp.frame = s.frame;
3045 flags |= eDisplayTransactionNeeded;
3046 }
3047 if (disp.viewport != s.viewport) {
3048 disp.viewport = s.viewport;
3049 flags |= eDisplayTransactionNeeded;
3050 }
3051 }
Michael Lentine47e45402014-07-18 15:34:25 -07003052 if (what & DisplayState::eDisplaySizeChanged) {
3053 if (disp.width != s.width) {
3054 disp.width = s.width;
3055 flags |= eDisplayTransactionNeeded;
3056 }
3057 if (disp.height != s.height) {
3058 disp.height = s.height;
3059 flags |= eDisplayTransactionNeeded;
3060 }
3061 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003062 }
3063 return flags;
3064}
3065
3066uint32_t SurfaceFlinger::setClientStateLocked(
3067 const sp<Client>& client,
3068 const layer_state_t& s)
3069{
3070 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003071 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003072 if (layer != 0) {
3073 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003074 bool geometryAppliesWithResize =
3075 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003076 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003077 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003078 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003079 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003080 }
3081 if (what & layer_state_t::eLayerChanged) {
3082 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003083 const auto& p = layer->getParent();
3084 if (p == nullptr) {
3085 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3086 if (layer->setLayer(s.z) && idx >= 0) {
3087 mCurrentState.layersSortedByZ.removeAt(idx);
3088 mCurrentState.layersSortedByZ.add(layer);
3089 // we need traversal (state changed)
3090 // AND transaction (list changed)
3091 flags |= eTransactionNeeded|eTraversalNeeded;
3092 }
3093 } else {
3094 if (p->setChildLayer(layer, s.z)) {
3095 flags |= eTransactionNeeded|eTraversalNeeded;
3096 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003097 }
3098 }
Robert Carrdb66e622017-04-10 16:55:57 -07003099 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003100 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003101 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003102 mCurrentState.layersSortedByZ.removeAt(idx);
3103 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003104 flags |= eTransactionNeeded|eTraversalNeeded;
3105 }
3106 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003107 if (what & layer_state_t::eSizeChanged) {
3108 if (layer->setSize(s.w, s.h)) {
3109 flags |= eTraversalNeeded;
3110 }
3111 }
3112 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003113 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003114 flags |= eTraversalNeeded;
3115 }
3116 if (what & layer_state_t::eMatrixChanged) {
3117 if (layer->setMatrix(s.matrix))
3118 flags |= eTraversalNeeded;
3119 }
3120 if (what & layer_state_t::eTransparentRegionChanged) {
3121 if (layer->setTransparentRegionHint(s.transparentRegion))
3122 flags |= eTraversalNeeded;
3123 }
Dan Stoza23116082015-06-18 14:58:39 -07003124 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003125 if (layer->setFlags(s.flags, s.mask))
3126 flags |= eTraversalNeeded;
3127 }
3128 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003129 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003130 flags |= eTraversalNeeded;
3131 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003132 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003133 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003134 flags |= eTraversalNeeded;
3135 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003136 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003137 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003138 // We only allow setting layer stacks for top level layers,
3139 // everything else inherits layer stack from its parent.
3140 if (layer->hasParent()) {
3141 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3142 layer->getName().string());
3143 } else if (idx < 0) {
3144 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3145 "that also does not appear in the top level layer list. Something"
3146 " has gone wrong.", layer->getName().string());
3147 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003148 mCurrentState.layersSortedByZ.removeAt(idx);
3149 mCurrentState.layersSortedByZ.add(layer);
3150 // we need traversal (state changed)
3151 // AND transaction (list changed)
3152 flags |= eTransactionNeeded|eTraversalNeeded;
3153 }
3154 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003155 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003156 if (s.barrierHandle != nullptr) {
3157 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3158 } else if (s.barrierGbp != nullptr) {
3159 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3160 if (authenticateSurfaceTextureLocked(gbp)) {
3161 const auto& otherLayer =
3162 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3163 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3164 } else {
3165 ALOGE("Attempt to defer transaction to to an"
3166 " unrecognized GraphicBufferProducer");
3167 }
3168 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003169 // We don't trigger a traversal here because if no other state is
3170 // changed, we don't want this to cause any more work
3171 }
Robert Carr1db73f62016-12-21 12:58:51 -08003172 if (what & layer_state_t::eReparentChildren) {
3173 if (layer->reparentChildren(s.reparentHandle)) {
3174 flags |= eTransactionNeeded|eTraversalNeeded;
3175 }
3176 }
Robert Carr9524cb32017-02-13 11:32:32 -08003177 if (what & layer_state_t::eDetachChildren) {
3178 layer->detachChildren();
3179 }
Robert Carrc3574f72016-03-24 12:19:32 -07003180 if (what & layer_state_t::eOverrideScalingModeChanged) {
3181 layer->setOverrideScalingMode(s.overrideScalingMode);
3182 // We don't trigger a traversal here because if no other state is
3183 // changed, we don't want this to cause any more work
3184 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003185 }
3186 return flags;
3187}
3188
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003189status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003190 const String8& name,
3191 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003192 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003193 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3194 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003196 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003197 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003198 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003199 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003200 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003201
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003202 status_t result = NO_ERROR;
3203
3204 sp<Layer> layer;
3205
Cody Northropbc755282017-03-31 12:00:08 -06003206 String8 uniqueName = getUniqueLayerName(name);
3207
Mathias Agopian3165cc22012-08-08 19:42:09 -07003208 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3209 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003210 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003211 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003212 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003213 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003214 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003215 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003216 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003217 handle, gbp, &layer);
3218 break;
3219 default:
3220 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221 break;
3222 }
3223
Dan Stoza7d89d062015-04-30 13:29:25 -07003224 if (result != NO_ERROR) {
3225 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003226 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003227
Chia-I Wuab0c3192017-08-01 11:29:00 -07003228 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3229 // TODO b/64227542
3230 if (windowType == 441731) {
3231 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3232 layer->setPrimaryDisplayOnly();
3233 }
3234
Albert Chaulk479c60c2017-01-27 14:21:34 -05003235 layer->setInfo(windowType, ownerUid);
3236
Robert Carr1f0a16a2016-10-24 16:27:39 -07003237 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003238 if (result != NO_ERROR) {
3239 return result;
3240 }
Irvelffc9efc2016-07-27 15:16:37 -07003241 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003242
3243 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003244 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003245}
3246
Cody Northropbc755282017-03-31 12:00:08 -06003247String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3248{
3249 bool matchFound = true;
3250 uint32_t dupeCounter = 0;
3251
3252 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3253 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3254
3255 // Loop over layers until we're sure there is no matching name
3256 while (matchFound) {
3257 matchFound = false;
3258 mDrawingState.traverseInZOrder([&](Layer* layer) {
3259 if (layer->getName() == uniqueName) {
3260 matchFound = true;
3261 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3262 }
3263 });
3264 }
3265
3266 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3267
3268 return uniqueName;
3269}
3270
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003271status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3272 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3273 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274{
3275 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003276 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 case PIXEL_FORMAT_TRANSPARENT:
3278 case PIXEL_FORMAT_TRANSLUCENT:
3279 format = PIXEL_FORMAT_RGBA_8888;
3280 break;
3281 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003282 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283 break;
3284 }
3285
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003286 *outLayer = new Layer(this, client, name, w, h, flags);
3287 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3288 if (err == NO_ERROR) {
3289 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003290 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003292
3293 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3294 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003295}
3296
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003297status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3298 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3299 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003300{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003301 *outLayer = new LayerDim(this, client, name, w, h, flags);
3302 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003303 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003304 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003305}
3306
Mathias Agopianac9fa422013-02-11 16:40:36 -08003307status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003308{
Robert Carr9524cb32017-02-13 11:32:32 -08003309 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003310 status_t err = NO_ERROR;
3311 sp<Layer> l(client->getLayerUser(handle));
3312 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003313 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003314 err = removeLayer(l);
3315 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3316 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003317 }
3318 return err;
3319}
3320
Mathias Agopian13127d82013-03-05 17:47:11 -08003321status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003322{
Mathias Agopian67106042013-03-14 19:18:13 -07003323 // called by ~LayerCleaner() when all references to the IBinder (handle)
3324 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003325 sp<Layer> l = layer.promote();
3326 if (l == nullptr) {
3327 // The layer has already been removed, carry on
3328 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003329 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003330 // If we have a parent, then we can continue to live as long as it does.
3331 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003332}
3333
Mathias Agopianb60314a2012-04-10 22:09:54 -07003334// ---------------------------------------------------------------------------
3335
Andy McFadden13a082e2012-08-24 10:16:42 -07003336void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003337 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003338 Vector<ComposerState> state;
3339 Vector<DisplayState> displays;
3340 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003341 d.what = DisplayState::eDisplayProjectionChanged |
3342 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003343 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003344 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003345 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003346 d.frame.makeInvalid();
3347 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003348 d.width = 0;
3349 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003350 displays.add(d);
3351 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003352 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3353 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003354
Dan Stoza9e56aa02015-11-02 13:00:03 -08003355 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3356 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003357 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003358
Brian Andersond0010582017-03-07 13:20:31 -08003359 // Use phase of 0 since phase is not known.
3360 // Use latency of 0, which will snap to the ideal latency.
3361 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003362}
3363
3364void SurfaceFlinger::initializeDisplays() {
3365 class MessageScreenInitialized : public MessageBase {
3366 SurfaceFlinger* flinger;
3367 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003368 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003369 virtual bool handler() {
3370 flinger->onInitializeDisplays();
3371 return true;
3372 }
3373 };
3374 sp<MessageBase> msg = new MessageScreenInitialized(this);
3375 postMessageAsync(msg); // we may be called from main thread, use async message
3376}
3377
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003378void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003379 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003380 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3381 this);
3382 int32_t type = hw->getDisplayType();
3383 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003384
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003385 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003386 return;
3387 }
3388
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003389 hw->setPowerMode(mode);
3390 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3391 ALOGW("Trying to set power mode for virtual display");
3392 return;
3393 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003394
Irvelffc9efc2016-07-27 15:16:37 -07003395 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003396 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003397 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3398 if (idx < 0) {
3399 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3400 return;
3401 }
3402 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3403 }
3404
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003405 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003406 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003407 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003408 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3409 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003410 // FIXME: eventthread only knows about the main display right now
3411 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003412 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003413 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003414
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003415 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003416 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003417 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003418
3419 struct sched_param param = {0};
3420 param.sched_priority = 1;
3421 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3422 ALOGW("Couldn't set SCHED_FIFO on display on");
3423 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003424 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003425 // Turn off the display
3426 struct sched_param param = {0};
3427 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3428 ALOGW("Couldn't set SCHED_OTHER on display off");
3429 }
3430
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003431 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003432 disableHardwareVsync(true); // also cancels any in-progress resync
3433
Mathias Agopiancde87a32012-09-13 14:09:01 -07003434 // FIXME: eventthread only knows about the main display right now
3435 mEventThread->onScreenReleased();
3436 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003437
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003438 getHwComposer().setPowerMode(type, mode);
3439 mVisibleRegionsDirty = true;
3440 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003441 } else if (mode == HWC_POWER_MODE_DOZE ||
3442 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003443 // Update display while dozing
3444 getHwComposer().setPowerMode(type, mode);
3445 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3446 // FIXME: eventthread only knows about the main display right now
3447 mEventThread->onScreenAcquired();
3448 resyncToHardwareVsync(true);
3449 }
3450 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3451 // Leave display going to doze
3452 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3453 disableHardwareVsync(true); // also cancels any in-progress resync
3454 // FIXME: eventthread only knows about the main display right now
3455 mEventThread->onScreenReleased();
3456 }
3457 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003458 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003459 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003460 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003461 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003462}
3463
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003464void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3465 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003466 SurfaceFlinger& mFlinger;
3467 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003468 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003469 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003470 MessageSetPowerMode(SurfaceFlinger& flinger,
3471 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3472 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003473 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003474 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003475 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003476 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003477 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003478 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003479 ALOGW("Attempt to set power mode = %d for virtual display",
3480 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003481 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003482 mFlinger.setPowerModeInternal(
3483 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003484 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003485 return true;
3486 }
3487 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003488 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003489 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003490}
3491
3492// ---------------------------------------------------------------------------
3493
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003494status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3495{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003496 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003497
Mathias Agopianbd115332013-04-18 16:41:04 -07003498 IPCThreadState* ipc = IPCThreadState::self();
3499 const int pid = ipc->getCallingPid();
3500 const int uid = ipc->getCallingUid();
3501 if ((uid != AID_SHELL) &&
3502 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003503 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003504 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003505 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003506 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003507 // (this would indicate SF is stuck, but we want to be able to
3508 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003509 status_t err = mStateLock.timedLock(s2ns(1));
3510 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003511 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003512 result.appendFormat(
3513 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3514 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003515 }
3516
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003517 bool dumpAll = true;
3518 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003519 size_t numArgs = args.size();
3520 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003521 if ((index < numArgs) &&
3522 (args[index] == String16("--list"))) {
3523 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003524 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003525 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003526 }
3527
3528 if ((index < numArgs) &&
3529 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003530 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003531 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003532 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003533 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003534
3535 if ((index < numArgs) &&
3536 (args[index] == String16("--latency-clear"))) {
3537 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003538 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003539 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003540 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003541
3542 if ((index < numArgs) &&
3543 (args[index] == String16("--dispsync"))) {
3544 index++;
3545 mPrimaryDispSync.dump(result);
3546 dumpAll = false;
3547 }
Dan Stozab90cf072015-03-05 11:05:59 -08003548
3549 if ((index < numArgs) &&
3550 (args[index] == String16("--static-screen"))) {
3551 index++;
3552 dumpStaticScreenStats(result);
3553 dumpAll = false;
3554 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003555
3556 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003557 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003558 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003559 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003560 dumpAll = false;
3561 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003562
3563 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3564 index++;
3565 dumpWideColorInfo(result);
3566 dumpAll = false;
3567 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003568 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003569
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003570 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003571 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003572 }
3573
Mathias Agopian9795c422009-08-26 16:36:26 -07003574 if (locked) {
3575 mStateLock.unlock();
3576 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003577 }
3578 write(fd, result.string(), result.size());
3579 return NO_ERROR;
3580}
3581
Dan Stozac7014012014-02-14 15:03:43 -08003582void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3583 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003584{
Robert Carr2047fae2016-11-28 14:09:09 -08003585 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003586 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003587 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003588}
3589
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003590void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003591 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003592{
3593 String8 name;
3594 if (index < args.size()) {
3595 name = String8(args[index]);
3596 index++;
3597 }
3598
Dan Stoza9e56aa02015-11-02 13:00:03 -08003599 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3600 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003601 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003602
3603 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003604 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003605 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003606 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003607 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003608 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003609 }
Robert Carr2047fae2016-11-28 14:09:09 -08003610 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003611 }
3612}
3613
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003614void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003615 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003616{
3617 String8 name;
3618 if (index < args.size()) {
3619 name = String8(args[index]);
3620 index++;
3621 }
3622
Robert Carr2047fae2016-11-28 14:09:09 -08003623 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003624 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003625 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003626 }
Robert Carr2047fae2016-11-28 14:09:09 -08003627 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003628
Svetoslavd85084b2014-03-20 10:28:31 -07003629 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003630}
3631
Jamie Gennis6547ff42013-07-16 20:12:42 -07003632// This should only be called from the main thread. Otherwise it would need
3633// the lock and should use mCurrentState rather than mDrawingState.
3634void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003635 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003636 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003637 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003638
3639 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3640}
3641
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003642void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003643{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003644 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003645 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3646
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003647 if (isLayerTripleBufferingDisabled())
3648 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003649
3650 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003651 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003652 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003653 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003654 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3655 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003656 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003657}
3658
Dan Stozab90cf072015-03-05 11:05:59 -08003659void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3660{
3661 result.appendFormat("Static screen stats:\n");
3662 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3663 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3664 float percent = 100.0f *
3665 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3666 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3667 b + 1, bucketTimeSec, percent);
3668 }
3669 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3670 float percent = 100.0f *
3671 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3672 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3673 NUM_BUCKETS - 1, bucketTimeSec, percent);
3674}
3675
Dan Stozae77c7662016-05-13 11:37:28 -07003676void SurfaceFlinger::recordBufferingStats(const char* layerName,
3677 std::vector<OccupancyTracker::Segment>&& history) {
3678 Mutex::Autolock lock(mBufferingStatsMutex);
3679 auto& stats = mBufferingStats[layerName];
3680 for (const auto& segment : history) {
3681 if (!segment.usedThirdBuffer) {
3682 stats.twoBufferTime += segment.totalTime;
3683 }
3684 if (segment.occupancyAverage < 1.0f) {
3685 stats.doubleBufferedTime += segment.totalTime;
3686 } else if (segment.occupancyAverage < 2.0f) {
3687 stats.tripleBufferedTime += segment.totalTime;
3688 }
3689 ++stats.numSegments;
3690 stats.totalTime += segment.totalTime;
3691 }
3692}
3693
Brian Andersond6927fb2016-07-23 23:37:30 -07003694void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3695 result.appendFormat("Layer frame timestamps:\n");
3696
3697 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3698 const size_t count = currentLayers.size();
3699 for (size_t i=0 ; i<count ; i++) {
3700 currentLayers[i]->dumpFrameEvents(result);
3701 }
3702}
3703
Dan Stozae77c7662016-05-13 11:37:28 -07003704void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3705 result.append("Buffering stats:\n");
3706 result.append(" [Layer name] <Active time> <Two buffer> "
3707 "<Double buffered> <Triple buffered>\n");
3708 Mutex::Autolock lock(mBufferingStatsMutex);
3709 typedef std::tuple<std::string, float, float, float> BufferTuple;
3710 std::map<float, BufferTuple, std::greater<float>> sorted;
3711 for (const auto& statsPair : mBufferingStats) {
3712 const char* name = statsPair.first.c_str();
3713 const BufferingStats& stats = statsPair.second;
3714 if (stats.numSegments == 0) {
3715 continue;
3716 }
3717 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3718 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3719 stats.totalTime;
3720 float doubleBufferRatio = static_cast<float>(
3721 stats.doubleBufferedTime) / stats.totalTime;
3722 float tripleBufferRatio = static_cast<float>(
3723 stats.tripleBufferedTime) / stats.totalTime;
3724 sorted.insert({activeTime, {name, twoBufferRatio,
3725 doubleBufferRatio, tripleBufferRatio}});
3726 }
3727 for (const auto& sortedPair : sorted) {
3728 float activeTime = sortedPair.first;
3729 const BufferTuple& values = sortedPair.second;
3730 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3731 std::get<0>(values).c_str(), activeTime,
3732 std::get<1>(values), std::get<2>(values),
3733 std::get<3>(values));
3734 }
3735 result.append("\n");
3736}
3737
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003738void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3739 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3740
3741 // TODO: print out if wide-color mode is active or not
3742
3743 for (size_t d = 0; d < mDisplays.size(); d++) {
3744 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3745 int32_t hwcId = displayDevice->getHwcDisplayId();
3746 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3747 continue;
3748 }
3749
3750 result.appendFormat("Display %d color modes:\n", hwcId);
3751 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3752 for (auto&& mode : modes) {
3753 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3754 }
3755
3756 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3757 result.appendFormat(" Current color mode: %s (%d)\n",
3758 decodeColorMode(currentMode).c_str(), currentMode);
3759 }
3760 result.append("\n");
3761}
3762
Mathias Agopian74d211a2013-04-22 16:55:35 +02003763void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3764 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003765{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003766 bool colorize = false;
3767 if (index < args.size()
3768 && (args[index] == String16("--color"))) {
3769 colorize = true;
3770 index++;
3771 }
3772
3773 Colorizer colorizer(colorize);
3774
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003775 // figure out if we're stuck somewhere
3776 const nsecs_t now = systemTime();
3777 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3778 const nsecs_t inTransaction(mDebugInTransaction);
3779 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3780 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3781
3782 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003783 * Dump library configuration.
3784 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003785
3786 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003787 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003788 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003789 appendSfConfigString(result);
3790 appendUiConfigString(result);
3791 appendGuiConfigString(result);
3792 result.append("\n");
3793
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003794 result.append("\nWide-Color information:\n");
3795 dumpWideColorInfo(result);
3796
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003797 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003798 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003799 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003800 result.append(SyncFeatures::getInstance().toString());
3801 result.append("\n");
3802
Dan Stoza9e56aa02015-11-02 13:00:03 -08003803 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3804
Andy McFadden41d67d72014-04-25 16:58:34 -07003805 colorizer.bold(result);
3806 result.append("DispSync configuration: ");
3807 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003808 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003809 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003810 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003811 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003812 result.append("\n");
3813
Dan Stozab90cf072015-03-05 11:05:59 -08003814 // Dump static screen stats
3815 result.append("\n");
3816 dumpStaticScreenStats(result);
3817 result.append("\n");
3818
Dan Stozae77c7662016-05-13 11:37:28 -07003819 dumpBufferingStats(result);
3820
Andy McFadden4803b742012-09-24 19:07:20 -07003821 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003822 * Dump the visible layer list
3823 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003824 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003825 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003826 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003827 mCurrentState.traverseInZOrder([&](Layer* layer) {
Kalle Raitaa099a242017-01-11 11:17:29 -08003828 result.append(to_string(layer->getLayerDebugInfo()).c_str());
Robert Carr2047fae2016-11-28 14:09:09 -08003829 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003830
3831 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003832 * Dump Display state
3833 */
3834
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003835 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003836 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003837 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003838 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3839 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003840 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003841 }
3842
3843 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003844 * Dump SurfaceFlinger global state
3845 */
3846
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003847 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003848 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003849 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003850
Mathias Agopian888c8222012-08-04 21:10:38 -07003851 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003852 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003853
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003854 colorizer.bold(result);
3855 result.appendFormat("EGL implementation : %s\n",
3856 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3857 colorizer.reset(result);
3858 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003859 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003860
Mathias Agopian875d8e12013-06-07 15:35:48 -07003861 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003862
Mathias Agopian42977342012-08-05 00:40:46 -07003863 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003864 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3865 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003866 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003867 " last eglSwapBuffers() time: %f us\n"
3868 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003869 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003870 " refresh-rate : %f fps\n"
3871 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003872 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003873 " gpu_to_cpu_unsupported : %d\n"
3874 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003875 mLastSwapBufferTime/1000.0,
3876 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003877 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003878 1e9 / activeConfig->getVsyncPeriod(),
3879 activeConfig->getDpiX(),
3880 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003881 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003882
Mathias Agopian74d211a2013-04-22 16:55:35 +02003883 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003884 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003885
Mathias Agopian74d211a2013-04-22 16:55:35 +02003886 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003887 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003888
3889 /*
3890 * VSYNC state
3891 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003892 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003893 result.append("\n");
3894
3895 /*
3896 * HWC layer minidump
3897 */
3898 for (size_t d = 0; d < mDisplays.size(); d++) {
3899 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3900 int32_t hwcId = displayDevice->getHwcDisplayId();
3901 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3902 continue;
3903 }
3904
3905 result.appendFormat("Display %d HWC layers:\n", hwcId);
3906 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003907 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003908 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003909 });
Dan Stozae22aec72016-08-01 13:20:59 -07003910 result.append("\n");
3911 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003912
3913 /*
3914 * Dump HWComposer state
3915 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003916 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003917 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003918 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003919 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003920 result.appendFormat(" h/w composer %s\n",
3921 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003922 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003923
3924 /*
3925 * Dump gralloc state
3926 */
3927 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3928 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003929
3930 /*
3931 * Dump VrFlinger state if in use.
3932 */
3933 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3934 result.append("VrFlinger state:\n");
3935 result.append(mVrFlinger->Dump().c_str());
3936 result.append("\n");
3937 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003938}
3939
Mathias Agopian13127d82013-03-05 17:47:11 -08003940const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003941SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003942 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003943 wp<IBinder> dpy;
3944 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3945 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3946 dpy = mDisplays.keyAt(i);
3947 break;
3948 }
3949 }
3950 if (dpy == NULL) {
3951 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3952 // Just use the primary display so we have something to return
3953 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3954 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003955 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003956}
3957
Keun young Park63f165f2012-08-31 10:53:36 -07003958bool SurfaceFlinger::startDdmConnection()
3959{
3960 void* libddmconnection_dso =
3961 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3962 if (!libddmconnection_dso) {
3963 return false;
3964 }
3965 void (*DdmConnection_start)(const char* name);
3966 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003967 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003968 if (!DdmConnection_start) {
3969 dlclose(libddmconnection_dso);
3970 return false;
3971 }
3972 (*DdmConnection_start)(getServiceName());
3973 return true;
3974}
3975
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003976status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003977 switch (code) {
3978 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003979 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003980 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003981 case CLEAR_ANIMATION_FRAME_STATS:
3982 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003983 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003984 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003985 {
3986 // codes that require permission check
3987 IPCThreadState* ipc = IPCThreadState::self();
3988 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003989 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003990 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003991 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003992 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003993 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003994 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003995 break;
3996 }
Robert Carr1db73f62016-12-21 12:58:51 -08003997 /*
3998 * Calling setTransactionState is safe, because you need to have been
3999 * granted a reference to Client* and Handle* to do anything with it.
4000 *
4001 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4002 */
4003 case SET_TRANSACTION_STATE:
4004 case CREATE_SCOPED_CONNECTION:
4005 {
4006 return OK;
4007 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004008 case CAPTURE_SCREEN:
4009 {
4010 // codes that require permission check
4011 IPCThreadState* ipc = IPCThreadState::self();
4012 const int pid = ipc->getCallingPid();
4013 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004014 if ((uid != AID_GRAPHICS) &&
4015 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004016 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004017 return PERMISSION_DENIED;
4018 }
4019 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004020 }
4021 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004022 return OK;
4023}
4024
4025status_t SurfaceFlinger::onTransact(
4026 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4027{
4028 status_t credentialCheck = CheckTransactCodeCredentials(code);
4029 if (credentialCheck != OK) {
4030 return credentialCheck;
4031 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004033 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4034 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004035 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004036 IPCThreadState* ipc = IPCThreadState::self();
4037 const int uid = ipc->getCallingUid();
4038 if (CC_UNLIKELY(uid != AID_SYSTEM
4039 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004040 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004041 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004042 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004043 return PERMISSION_DENIED;
4044 }
4045 int n;
4046 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004047 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004048 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004049 return NO_ERROR;
4050 case 1002: // SHOW_UPDATES
4051 n = data.readInt32();
4052 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004053 invalidateHwcGeometry();
4054 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004055 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004056 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004057 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004058 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004059 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004060 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004061 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004062 setTransactionFlags(
4063 eTransactionNeeded|
4064 eDisplayTransactionNeeded|
4065 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004066 return NO_ERROR;
4067 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004068 case 1006:{ // send empty update
4069 signalRefresh();
4070 return NO_ERROR;
4071 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004072 case 1008: // toggle use of hw composer
4073 n = data.readInt32();
4074 mDebugDisableHWC = n ? 1 : 0;
4075 invalidateHwcGeometry();
4076 repaintEverything();
4077 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004078 case 1009: // toggle use of transform hint
4079 n = data.readInt32();
4080 mDebugDisableTransformHint = n ? 1 : 0;
4081 invalidateHwcGeometry();
4082 repaintEverything();
4083 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004084 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004085 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004086 reply->writeInt32(0);
4087 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004088 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004089 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004090 return NO_ERROR;
4091 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004092 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004093 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004094 return NO_ERROR;
4095 }
4096 case 1014: {
4097 // daltonize
4098 n = data.readInt32();
4099 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004100 case 1:
4101 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4102 break;
4103 case 2:
4104 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4105 break;
4106 case 3:
4107 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4108 break;
4109 default:
4110 mDaltonizer.setType(ColorBlindnessType::None);
4111 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004112 }
4113 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004114 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004115 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004116 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004117 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004118 invalidateHwcGeometry();
4119 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004120 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004121 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004122 case 1015: {
4123 // apply a color matrix
4124 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004125 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004126 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004127 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004128 for (size_t j = 0; j < 4; j++) {
4129 mColorMatrix[i][j] = data.readFloat();
4130 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004131 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004132 } else {
4133 mColorMatrix = mat4();
4134 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004135
4136 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4137 // the division by w in the fragment shader
4138 float4 lastRow(transpose(mColorMatrix)[3]);
4139 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4140 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4141 }
4142
Alan Viverette9c5a3332013-09-12 20:04:35 -07004143 invalidateHwcGeometry();
4144 repaintEverything();
4145 return NO_ERROR;
4146 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004147 // This is an experimental interface
4148 // Needs to be shifted to proper binder interface when we productize
4149 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004150 n = data.readInt32();
4151 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004152 return NO_ERROR;
4153 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004154 case 1017: {
4155 n = data.readInt32();
4156 mForceFullDamage = static_cast<bool>(n);
4157 return NO_ERROR;
4158 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004159 case 1018: { // Modify Choreographer's phase offset
4160 n = data.readInt32();
4161 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4162 return NO_ERROR;
4163 }
4164 case 1019: { // Modify SurfaceFlinger's phase offset
4165 n = data.readInt32();
4166 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4167 return NO_ERROR;
4168 }
Irvel468051e2016-06-13 16:44:44 -07004169 case 1020: { // Layer updates interceptor
4170 n = data.readInt32();
4171 if (n) {
4172 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004173 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004174 }
4175 else{
4176 ALOGV("Interceptor disabled");
4177 mInterceptor.disable();
4178 }
4179 return NO_ERROR;
4180 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004181 case 1021: { // Disable HWC virtual displays
4182 n = data.readInt32();
4183 mUseHwcVirtualDisplays = !n;
4184 return NO_ERROR;
4185 }
Romain Guy0147a172017-06-01 13:53:56 -07004186 case 1022: { // Set saturation boost
4187 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4188
4189 invalidateHwcGeometry();
4190 repaintEverything();
4191 return NO_ERROR;
4192 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004193 }
4194 }
4195 return err;
4196}
4197
Steven Thomas6d8110b2017-08-31 18:24:21 -07004198void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004199 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004200 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004201}
4202
Steven Thomas6d8110b2017-08-31 18:24:21 -07004203void SurfaceFlinger::repaintEverything() {
4204 ConditionalLock _l(mStateLock,
4205 std::this_thread::get_id() != mMainThreadId);
4206 repaintEverythingLocked();
4207}
4208
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004209// Checks that the requested width and height are valid and updates them to the display dimensions
4210// if they are set to 0
4211static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4212 Transform::orientation_flags rotation,
4213 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4214 // get screen geometry
4215 uint32_t displayWidth = displayDevice->getWidth();
4216 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004217
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004218 if (rotation & Transform::ROT_90) {
4219 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004220 }
4221
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004222 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4223 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4224 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4225 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004226 }
4227
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004228 if (*requestedWidth == 0) {
4229 *requestedWidth = displayWidth;
4230 }
4231 if (*requestedHeight == 0) {
4232 *requestedHeight = displayHeight;
4233 }
4234
4235 return NO_ERROR;
4236}
4237
4238// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4239class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004240public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004241 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4242 ~WindowDisconnector() {
4243 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004244 }
4245
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004246private:
4247 ANativeWindow* mWindow;
4248 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004249};
4250
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004251static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4252 uint32_t requestedHeight, bool hasWideColorDisplay,
4253 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4254 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4255 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4256
4257 int err = 0;
4258 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4259 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4260 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4261 err |= native_window_set_usage(window, usage);
4262
4263 if (hasWideColorDisplay) {
4264 err |= native_window_set_buffers_data_space(window,
4265 renderEngineUsesWideColor
4266 ? HAL_DATASPACE_DISPLAY_P3
4267 : HAL_DATASPACE_V0_SRGB);
4268 }
4269
4270 if (err != NO_ERROR) {
4271 return BAD_VALUE;
4272 }
4273
4274 /* TODO: Once we have the sync framework everywhere this can use
4275 * server-side waits on the fence that dequeueBuffer returns.
4276 */
4277 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4278 if (err != NO_ERROR) {
4279 return err;
4280 }
4281
4282 return NO_ERROR;
4283}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004284
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004285status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4286 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004287 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004288 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004289 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004290 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004291
4292 if (CC_UNLIKELY(display == 0))
4293 return BAD_VALUE;
4294
4295 if (CC_UNLIKELY(producer == 0))
4296 return BAD_VALUE;
4297
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004298 // if we have secure windows on this display, never allow the screen capture
4299 // unless the producer interface is local (i.e.: we can take a screenshot for
4300 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004301 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004302
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004303 // Convert to surfaceflinger's internal rotation type.
4304 Transform::orientation_flags rotationFlags;
4305 switch (rotation) {
4306 case ISurfaceComposer::eRotateNone:
4307 rotationFlags = Transform::ROT_0;
4308 break;
4309 case ISurfaceComposer::eRotate90:
4310 rotationFlags = Transform::ROT_90;
4311 break;
4312 case ISurfaceComposer::eRotate180:
4313 rotationFlags = Transform::ROT_180;
4314 break;
4315 case ISurfaceComposer::eRotate270:
4316 rotationFlags = Transform::ROT_270;
4317 break;
4318 default:
4319 rotationFlags = Transform::ROT_0;
4320 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4321 break;
4322 }
4323
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004324 { // Autolock scope
4325 Mutex::Autolock lock(mStateLock);
4326 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4327 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004328 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004329
4330 // create a surface (because we're a producer, and we need to
4331 // dequeue/queue a buffer)
4332 sp<Surface> surface = new Surface(producer, false);
4333
4334 // Put the screenshot Surface into async mode so that
4335 // Layer::headFenceHasSignaled will always return true and we'll latch the
4336 // first buffer regardless of whether or not its acquire fence has
4337 // signaled. This is needed to avoid a race condition in the rotation
4338 // animation. See b/30209608
4339 surface->setAsyncMode(true);
4340
4341 ANativeWindow* window = surface.get();
4342
4343 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4344 if (result != NO_ERROR) {
4345 return result;
4346 }
4347 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4348
4349 ANativeWindowBuffer* buffer = nullptr;
4350 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4351 getRenderEngine().usesWideColor(), &buffer);
4352 if (result != NO_ERROR) {
4353 return result;
4354 }
4355
4356 // This mutex protects syncFd and captureResult for communication of the return values from the
4357 // main thread back to this Binder thread
4358 std::mutex captureMutex;
4359 std::condition_variable captureCondition;
4360 std::unique_lock<std::mutex> captureLock(captureMutex);
4361 int syncFd = -1;
4362 std::optional<status_t> captureResult;
4363
4364 sp<LambdaMessage> message = new LambdaMessage([&]() {
4365 // If there is a refresh pending, bug out early and tell the binder thread to try again
4366 // after the refresh.
4367 if (mRefreshPending) {
4368 ATRACE_NAME("Skipping screenshot for now");
4369 std::unique_lock<std::mutex> captureLock(captureMutex);
4370 captureResult = std::make_optional<status_t>(EAGAIN);
4371 captureCondition.notify_one();
4372 return;
4373 }
4374
4375 status_t result = NO_ERROR;
4376 int fd = -1;
4377 {
4378 Mutex::Autolock _l(mStateLock);
4379 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4380 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4381 minLayerZ, maxLayerZ, useIdentityTransform,
4382 rotationFlags, isLocalScreenshot, &fd);
4383 }
4384
4385 {
4386 std::unique_lock<std::mutex> captureLock(captureMutex);
4387 syncFd = fd;
4388 captureResult = std::make_optional<status_t>(result);
4389 captureCondition.notify_one();
4390 }
4391 });
4392
4393 result = postMessageAsync(message);
4394 if (result == NO_ERROR) {
4395 captureCondition.wait(captureLock, [&]() { return captureResult; });
4396 while (*captureResult == EAGAIN) {
4397 captureResult.reset();
4398 result = postMessageAsync(message);
4399 if (result != NO_ERROR) {
4400 return result;
4401 }
4402 captureCondition.wait(captureLock, [&]() { return captureResult; });
4403 }
4404 result = *captureResult;
4405 }
4406
4407 if (result == NO_ERROR) {
4408 // queueBuffer takes ownership of syncFd
4409 result = window->queueBuffer(window, buffer, syncFd);
4410 }
4411
4412 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004413}
4414
Mathias Agopian180f10d2013-04-10 22:55:41 -07004415
4416void SurfaceFlinger::renderScreenImplLocked(
4417 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004418 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004419 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004420 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004421{
4422 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004423 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004424
4425 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004426 const int32_t hw_w = hw->getWidth();
4427 const int32_t hw_h = hw->getHeight();
4428 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004429 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004430
Dan Stozac1879002014-05-22 15:59:05 -07004431 // if a default or invalid sourceCrop is passed in, set reasonable values
4432 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4433 !sourceCrop.isValid()) {
4434 sourceCrop.setLeftTop(Point(0, 0));
4435 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4436 }
4437
4438 // ensure that sourceCrop is inside screen
4439 if (sourceCrop.left < 0) {
4440 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4441 }
Dan Stozabe31f442014-06-11 11:20:54 -07004442 if (sourceCrop.right > hw_w) {
4443 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004444 }
4445 if (sourceCrop.top < 0) {
4446 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4447 }
Dan Stozabe31f442014-06-11 11:20:54 -07004448 if (sourceCrop.bottom > hw_h) {
4449 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004450 }
4451
Romain Guy88d37dd2017-05-26 17:57:05 -07004452#ifdef USE_HWC2
4453 engine.setWideColor(hw->getWideColorSupport());
4454 engine.setColorMode(hw->getActiveColorMode());
4455#endif
4456
Mathias Agopian180f10d2013-04-10 22:55:41 -07004457 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004458 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004459
4460 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004461 engine.setViewportAndProjection(
4462 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004463 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004464
4465 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004466 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004467
Robert Carr1f0a16a2016-10-24 16:27:39 -07004468 // We loop through the first level of layers without traversing,
4469 // as we need to interpret min/max layer Z in the top level Z space.
4470 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004471 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004472 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004473 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004474 const Layer::State& state(layer->getDrawingState());
4475 if (state.z < minLayerZ || state.z > maxLayerZ) {
4476 continue;
4477 }
Dan Stoza412903f2017-04-27 13:42:17 -07004478 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004479 if (!layer->isVisible()) {
4480 return;
4481 }
4482 if (filtering) layer->setFiltering(true);
4483 layer->draw(hw, useIdentityTransform);
4484 if (filtering) layer->setFiltering(false);
4485 });
4486 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004487
Mathias Agopian931bda12013-08-28 18:11:46 -07004488 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004489}
4490
Dan Stozaabcda352017-06-01 14:37:39 -07004491// A simple RAII class that holds an EGLImage and destroys it either:
4492// a) When the destroy() method is called
4493// b) When the object goes out of scope
4494class ImageHolder {
4495public:
4496 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4497 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004498
Dan Stozaabcda352017-06-01 14:37:39 -07004499 void destroy() {
4500 if (mImage != EGL_NO_IMAGE_KHR) {
4501 eglDestroyImageKHR(mDisplay, mImage);
4502 mImage = EGL_NO_IMAGE_KHR;
4503 }
4504 }
4505
4506private:
4507 const EGLDisplay mDisplay;
4508 EGLImageKHR mImage;
4509};
4510
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004511status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4512 ANativeWindowBuffer* buffer, Rect sourceCrop,
4513 uint32_t reqWidth, uint32_t reqHeight,
4514 int32_t minLayerZ, int32_t maxLayerZ,
4515 bool useIdentityTransform,
4516 Transform::orientation_flags rotation,
4517 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004518 ATRACE_CALL();
4519
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004520 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004521 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004522 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004523 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004524 (state.z < minLayerZ || state.z > maxLayerZ)) {
4525 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004526 }
Dan Stoza412903f2017-04-27 13:42:17 -07004527 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004528 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4529 layer->isSecure());
4530 });
4531 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004532
4533 if (!isLocalScreenshot && secureLayerIsVisible) {
4534 ALOGW("FB is protected: PERMISSION_DENIED");
4535 return PERMISSION_DENIED;
4536 }
4537
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004538 int syncFd = -1;
4539 // create an EGLImage from the buffer so we can later
4540 // turn it into a texture
4541 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4542 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4543 if (image == EGL_NO_IMAGE_KHR) {
4544 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004545 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004546
Dan Stozaabcda352017-06-01 14:37:39 -07004547 // This will automatically destroy the image if we return before calling its destroy method
4548 ImageHolder imageHolder(mEGLDisplay, image);
4549
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004550 // this binds the given EGLImage as a framebuffer for the
4551 // duration of this scope.
4552 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004553 if (imageBond.getStatus() != NO_ERROR) {
4554 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004555 return INVALID_OPERATION;
4556 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004557
Dan Stozaabcda352017-06-01 14:37:39 -07004558 // this will in fact render into our dequeued buffer
4559 // via an FBO, which means we didn't have to create
4560 // an EGLSurface and therefore we're not
4561 // dependent on the context's EGLConfig.
4562 renderScreenImplLocked(
4563 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4564 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004565
Dan Stozaabcda352017-06-01 14:37:39 -07004566 // Attempt to create a sync khr object that can produce a sync point. If that
4567 // isn't available, create a non-dupable sync object in the fallback path and
4568 // wait on it directly.
4569 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4570 if (!DEBUG_SCREENSHOTS) {
4571 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4572 // native fence fd will not be populated until flush() is done.
4573 getRenderEngine().flush();
4574 }
4575
4576 if (sync != EGL_NO_SYNC_KHR) {
4577 // get the sync fd
4578 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4579 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4580 ALOGW("captureScreen: failed to dup sync khr object");
4581 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004582 }
Dan Stozaabcda352017-06-01 14:37:39 -07004583 eglDestroySyncKHR(mEGLDisplay, sync);
4584 } else {
4585 // fallback path
4586 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004587 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004588 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4589 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4590 EGLint eglErr = eglGetError();
4591 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4592 ALOGW("captureScreen: fence wait timed out");
4593 } else {
4594 ALOGW_IF(eglErr != EGL_SUCCESS,
4595 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004596 }
4597 eglDestroySyncKHR(mEGLDisplay, sync);
4598 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004599 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004600 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004601 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004602 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004603
4604 if (DEBUG_SCREENSHOTS) {
4605 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4606 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4607 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4608 hw, minLayerZ, maxLayerZ);
4609 delete [] pixels;
4610 }
4611
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004612 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004613 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004614
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004615 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004616}
4617
Mathias Agopiand5556842013-09-19 17:08:37 -07004618void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004619 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004620 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004621 for (size_t y=0 ; y<h ; y++) {
4622 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4623 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004624 if (p[x] != 0xFF000000) return;
4625 }
4626 }
4627 ALOGE("*** we just took a black screenshot ***\n"
4628 "requested minz=%d, maxz=%d, layerStack=%d",
4629 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004630
Robert Carr2047fae2016-11-28 14:09:09 -08004631 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004632 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004633 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004634 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004635 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004636 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004637 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4638 layer->isVisible() ? '+' : '-',
4639 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004640 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004641 i++;
4642 });
4643 }
4644 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004645 }
4646}
4647
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004648// ---------------------------------------------------------------------------
4649
Dan Stoza412903f2017-04-27 13:42:17 -07004650void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4651 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004652}
4653
Dan Stoza412903f2017-04-27 13:42:17 -07004654void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4655 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004656}
4657
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004658}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004659
4660
4661#if defined(__gl_h_)
4662#error "don't include gl/gl.h in this file"
4663#endif
4664
4665#if defined(__gl2_h_)
4666#error "don't include gl2/gl2.h in this file"
4667#endif