blob: 5982422658d55cc84d004283692e490a43bba5c0 [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"
chaviw13fdc492017-06-27 12:40:18 -070076#include "ColorLayer.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093#define DISPLAY_COUNT 1
94
Mathias Agopianfee2b462013-07-03 12:34:01 -070095/*
96 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
97 * black pixels.
98 */
99#define DEBUG_SCREENSHOTS false
100
Jiyong Park00b15b82017-08-10 20:30:56 +0900101extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
Mathias Agopianca088332013-03-28 17:44:13 -0700102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
Steven Thomasb02664d2017-07-26 18:48:28 -0700108namespace {
109class ConditionalLock {
110public:
111 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
112 if (lock) {
113 mMutex.lock();
114 }
115 }
116 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
117private:
118 Mutex& mMutex;
119 bool mLocked;
120};
121} // namespace anonymous
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800131int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
132int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700133bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700134int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700135bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800136uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800137bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800138bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800139int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700158 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700160 mTransactionPending(false),
161 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700162 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700163 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700164 mRepaintEverything(0),
Kalle Raitaa099a242017-01-11 11:17:29 -0800165 mHwcServiceName(getHwcServiceName()),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800166 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800168 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800170 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800171 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800172 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700173 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700174 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700175 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700176 mDebugInSwapBuffers(0),
177 mLastSwapBufferTime(0),
178 mDebugInTransaction(0),
179 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700180 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700181 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800182 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000183 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700184 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700185 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700186 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800187 mHasPoweredOff(false),
188 mFrameBuckets(),
189 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700190 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800191 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700192 mVrFlingerRequestsDisplay(false),
193 mMainThreadId(std::this_thread::get_id()),
194 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800196 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800197
198 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
199 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
200
201 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
202 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
203
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800204 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
205 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700207 useContextPriority = getBool< ISurfaceFlingerConfigs,
208 &ISurfaceFlingerConfigs::useContextPriority>(false);
209
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700210 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
211 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
212
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700213 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
214 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
215
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
217 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
218
Steven Thomas050b2c82017-03-06 11:45:16 -0800219 // Vr flinger is only enabled on Daydream ready devices.
220 useVrFlinger = getBool< ISurfaceFlingerConfigs,
221 &ISurfaceFlingerConfigs::useVrFlinger>(false);
222
Fabien Sanglard1971b632017-03-10 14:50:03 -0800223 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
224 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
225
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600226 hasWideColorDisplay =
227 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
228
Saurabh Shahf4174532017-07-13 10:45:07 -0700229 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
230
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 // debugging stuff...
232 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700233
Mathias Agopianb4b17302013-03-20 18:36:41 -0700234 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700235 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 property_get("debug.sf.showupdates", value, "0");
238 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240 property_get("debug.sf.ddms", value, "0");
241 mDebugDDMS = atoi(value);
242 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700243 if (!startDdmConnection()) {
244 // start failed, and DDMS debugging not enabled
245 mDebugDDMS = 0;
246 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700247 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700248 ALOGI_IF(mDebugRegion, "showupdates enabled");
249 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700250
251 property_get("debug.sf.disable_backpressure", value, "0");
252 mPropagateBackpressure = !atoi(value);
253 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700254
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800255 property_get("debug.sf.enable_hwc_vds", value, "0");
256 mUseHwcVirtualDisplays = atoi(value);
257 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800258
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800259 property_get("ro.sf.disable_triple_buffer", value, "1");
260 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800261 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700262
Romain Guy11d63f42017-07-20 12:47:14 -0700263 // We should be reading 'persist.sys.sf.color_saturation' here
264 // but since /data may be encrypted, we need to wait until after vold
265 // comes online to attempt to read the property. The property is
266 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800267
268 if (useTrebleTestingOverride()) {
269 // Without the override SurfaceFlinger cannot connect to HIDL
270 // services that are not listed in the manifests. Considered
271 // deriving the setting from the set service name, but it
272 // would be brittle if the name that's not 'default' is used
273 // for production purposes later on.
274 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800278void SurfaceFlinger::onFirstRef()
279{
280 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800281}
282
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283SurfaceFlinger::~SurfaceFlinger()
284{
Mathias Agopiana4912602012-07-12 14:25:33 -0700285 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
286 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
287 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288}
289
Dan Stozac7014012014-02-14 15:03:43 -0800290void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800291{
292 // the window manager died on us. prepare its eulogy.
293
Andy McFadden13a082e2012-08-24 10:16:42 -0700294 // restore initial conditions (default device unblank, etc)
295 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800296
297 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700298 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800299}
300
Robert Carr1db73f62016-12-21 12:58:51 -0800301static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700302 status_t err = client->initCheck();
303 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800304 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 }
Robert Carr1db73f62016-12-21 12:58:51 -0800306 return nullptr;
307}
308
309sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
310 return initClient(new Client(this));
311}
312
313sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
314 const sp<IGraphicBufferProducer>& gbp) {
315 if (authenticateSurfaceTexture(gbp) == false) {
316 return nullptr;
317 }
318 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
319 if (layer == nullptr) {
320 return nullptr;
321 }
322
323 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324}
325
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700326sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
327 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700328{
329 class DisplayToken : public BBinder {
330 sp<SurfaceFlinger> flinger;
331 virtual ~DisplayToken() {
332 // no more references, this display must be terminated
333 Mutex::Autolock _l(flinger->mStateLock);
334 flinger->mCurrentState.displays.removeItem(this);
335 flinger->setTransactionFlags(eDisplayTransactionNeeded);
336 }
337 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700338 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700339 : flinger(flinger) {
340 }
341 };
342
343 sp<BBinder> token = new DisplayToken(this);
344
345 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700346 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700347 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700348 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700349 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700350 return token;
351}
352
Jesse Hall6c913be2013-08-08 12:15:49 -0700353void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
354 Mutex::Autolock _l(mStateLock);
355
356 ssize_t idx = mCurrentState.displays.indexOfKey(display);
357 if (idx < 0) {
358 ALOGW("destroyDisplay: invalid display token");
359 return;
360 }
361
362 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
363 if (!info.isVirtualDisplay()) {
364 ALOGE("destroyDisplay called for non-virtual display");
365 return;
366 }
Irvelffc9efc2016-07-27 15:16:37 -0700367 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700368 mCurrentState.displays.removeItemsAt(idx);
369 setTransactionFlags(eDisplayTransactionNeeded);
370}
371
Jesse Hall692c7232012-11-08 15:41:56 -0800372void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800373 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800374 ALOGW_IF(mBuiltinDisplays[type],
375 "Overwriting display token for display type %d", type);
376 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800377 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700378 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800379 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700380 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800381}
382
Mathias Agopiane57f2922012-08-09 16:29:12 -0700383sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700384 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700385 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
386 return NULL;
387 }
Jesse Hall692c7232012-11-08 15:41:56 -0800388 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700389}
390
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800391void SurfaceFlinger::bootFinished()
392{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700393 if (mStartPropertySetThread->join() != NO_ERROR) {
394 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800395 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396 const nsecs_t now = systemTime();
397 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000398 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700399
400 // wait patiently for the window manager death
401 const String16 name("window");
402 sp<IBinder> window(defaultServiceManager()->getService(name));
403 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700404 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700405 }
406
Steven Thomas050b2c82017-03-06 11:45:16 -0800407 if (mVrFlinger) {
408 mVrFlinger->OnBootFinished();
409 }
410
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700411 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700412 // formerly we would just kill the process, but we now ask it to exit so it
413 // can choose where to stop the animation.
414 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700415
416 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
417 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
418 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700419
Thierry Strudel2924d012017-08-14 15:19:37 -0700420 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700421 readPersistentProperties();
422 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700423 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Mathias Agopian3f844832013-08-07 21:24:32 -0700426void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700427 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700428 RenderEngine& engine;
429 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700430 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700431 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
432 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700433 }
434 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700435 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700436 return true;
437 }
438 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700439 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700440}
441
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442class DispSyncSource : public VSyncSource, private DispSync::Callback {
443public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700444 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000445 const char* name) :
446 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700447 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700448 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000449 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
450 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700451 mDispSync(dispSync),
452 mCallbackMutex(),
453 mCallback(),
454 mVsyncMutex(),
455 mPhaseOffset(phaseOffset),
456 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700457
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 virtual ~DispSyncSource() {}
459
460 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700461 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000463 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700464 static_cast<DispSync::Callback*>(this));
465 if (err != NO_ERROR) {
466 ALOGE("error registering vsync callback: %s (%d)",
467 strerror(-err), err);
468 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700469 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470 } else {
471 status_t err = mDispSync->removeEventListener(
472 static_cast<DispSync::Callback*>(this));
473 if (err != NO_ERROR) {
474 ALOGE("error unregistering vsync callback: %s (%d)",
475 strerror(-err), err);
476 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700477 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700478 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700479 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 }
481
482 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700483 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700484 mCallback = callback;
485 }
486
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700487 virtual void setPhaseOffset(nsecs_t phaseOffset) {
488 Mutex::Autolock lock(mVsyncMutex);
489
490 // Normalize phaseOffset to [0, period)
491 auto period = mDispSync->getPeriod();
492 phaseOffset %= period;
493 if (phaseOffset < 0) {
494 // If we're here, then phaseOffset is in (-period, 0). After this
495 // operation, it will be in (0, period)
496 phaseOffset += period;
497 }
498 mPhaseOffset = phaseOffset;
499
500 // If we're not enabled, we don't need to mess with the listeners
501 if (!mEnabled) {
502 return;
503 }
504
505 // Remove the listener with the old offset
506 status_t err = mDispSync->removeEventListener(
507 static_cast<DispSync::Callback*>(this));
508 if (err != NO_ERROR) {
509 ALOGE("error unregistering vsync callback: %s (%d)",
510 strerror(-err), err);
511 }
512
513 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000514 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700515 static_cast<DispSync::Callback*>(this));
516 if (err != NO_ERROR) {
517 ALOGE("error registering vsync callback: %s (%d)",
518 strerror(-err), err);
519 }
520 }
521
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522private:
523 virtual void onDispSyncEvent(nsecs_t when) {
524 sp<VSyncSource::Callback> callback;
525 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700526 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527 callback = mCallback;
528
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700529 if (mTraceVsync) {
530 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700531 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700532 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533 }
534
535 if (callback != NULL) {
536 callback->onVSyncEvent(when);
537 }
538 }
539
Tim Murray4a4e4a22016-04-19 16:29:23 +0000540 const char* const mName;
541
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 int mValue;
543
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700544 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700545 const String8 mVsyncOnLabel;
546 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700547
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700548 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700549
550 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700551 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700552
553 Mutex mVsyncMutex; // Protects the following
554 nsecs_t mPhaseOffset;
555 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700556};
557
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700558class InjectVSyncSource : public VSyncSource {
559public:
560 InjectVSyncSource() {}
561
562 virtual ~InjectVSyncSource() {}
563
564 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
565 std::lock_guard<std::mutex> lock(mCallbackMutex);
566 mCallback = callback;
567 }
568
569 virtual void onInjectSyncEvent(nsecs_t when) {
570 std::lock_guard<std::mutex> lock(mCallbackMutex);
571 mCallback->onVSyncEvent(when);
572 }
573
574 virtual void setVSyncEnabled(bool) {}
575 virtual void setPhaseOffset(nsecs_t) {}
576
577private:
578 std::mutex mCallbackMutex; // Protects the following
579 sp<VSyncSource::Callback> mCallback;
580};
581
Wei Wangf9b05ee2017-07-19 20:59:39 -0700582// Do not call property_set on main thread which will be blocked by init
583// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700584void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700585 ALOGI( "SurfaceFlinger's main thread ready to run. "
586 "Initializing graphics H/W...");
587
Thierry Strudel2924d012017-08-14 15:19:37 -0700588 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900589
Steven Thomasb02664d2017-07-26 18:48:28 -0700590 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800591
Steven Thomasb02664d2017-07-26 18:48:28 -0700592 // initialize EGL for the default display
593 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
594 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800595
Steven Thomasb02664d2017-07-26 18:48:28 -0700596 // start the EventThread
597 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
598 vsyncPhaseOffsetNs, true, "app");
599 mEventThread = new EventThread(vsyncSrc, *this, false);
600 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
601 sfVsyncPhaseOffsetNs, true, "sf");
602 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
603 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800604
Steven Thomasb02664d2017-07-26 18:48:28 -0700605 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
606 struct sched_param param = {0};
607 param.sched_priority = 2;
608 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
609 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
610 }
611 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
612 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800613 }
614
Steven Thomasb02664d2017-07-26 18:48:28 -0700615 // Get a RenderEngine for the given display / config (can't fail)
616 mRenderEngine = RenderEngine::create(mEGLDisplay,
617 HAL_PIXEL_FORMAT_RGBA_8888,
618 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 // retrieve the EGL context that was selected/created
621 mEGLContext = mRenderEngine->getEGLContext();
622
623 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
624 "couldn't create EGLContext");
625
626 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
627 "Starting with vr flinger active is not currently supported.");
628 mHwc.reset(new HWComposer(mHwcServiceName));
629 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800630
Steven Thomas050b2c82017-03-06 11:45:16 -0800631 if (useVrFlinger) {
632 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700633 // This callback is called from the vr flinger dispatch thread. We
634 // need to call signalTransaction(), which requires holding
635 // mStateLock when we're not on the main thread. Acquiring
636 // mStateLock from the vr flinger dispatch thread might trigger a
637 // deadlock in surface flinger (see b/66916578), so post a message
638 // to be handled on the main thread instead.
639 sp<LambdaMessage> message = new LambdaMessage([=]() {
640 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
641 mVrFlingerRequestsDisplay = requestDisplay;
642 signalTransaction();
643 });
644 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800645 };
646 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
647 vrFlingerRequestDisplayCallback);
648 if (!mVrFlinger) {
649 ALOGE("Failed to start vrflinger");
650 }
651 }
652
Jamie Gennisd1700752013-10-14 12:22:52 -0700653 mEventControlThread = new EventControlThread(this);
654 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
655
Mathias Agopian92a979a2012-08-02 18:32:23 -0700656 // initialize our drawing state
657 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700658
Andy McFadden13a082e2012-08-24 10:16:42 -0700659 // set initial conditions (e.g. unblank default device)
660 initializeDisplays();
661
Dan Stoza4e637772016-07-28 13:31:51 -0700662 mRenderEngine->primeCache();
663
Wei Wangf9b05ee2017-07-19 20:59:39 -0700664 // Inform native graphics APIs whether the present timestamp is supported:
665 if (getHwComposer().hasCapability(
666 HWC2::Capability::PresentFenceIsNotReliable)) {
667 mStartPropertySetThread = new StartPropertySetThread(false);
668 } else {
669 mStartPropertySetThread = new StartPropertySetThread(true);
670 }
671
672 if (mStartPropertySetThread->Start() != NO_ERROR) {
673 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800674 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800675
Dan Stoza9e56aa02015-11-02 13:00:03 -0800676 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700677}
678
Romain Guy11d63f42017-07-20 12:47:14 -0700679void SurfaceFlinger::readPersistentProperties() {
680 char value[PROPERTY_VALUE_MAX];
681
682 property_get("persist.sys.sf.color_saturation", value, "1.0");
683 mSaturation = atof(value);
684 ALOGV("Saturation is set to %.2f", mSaturation);
685}
686
Mathias Agopiana67e4182012-06-19 17:26:12 -0700687void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800688 // Start boot animation service by setting a property mailbox
689 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700690 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800691 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 if (mStartPropertySetThread->join() != NO_ERROR) {
693 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800694 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700695}
696
Mathias Agopian875d8e12013-06-07 15:35:48 -0700697size_t SurfaceFlinger::getMaxTextureSize() const {
698 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700699}
700
Mathias Agopian875d8e12013-06-07 15:35:48 -0700701size_t SurfaceFlinger::getMaxViewportDims() const {
702 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700703}
704
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800705// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800706
Jamie Gennis582270d2011-08-17 18:19:00 -0700707bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800708 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800709 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800710 return authenticateSurfaceTextureLocked(bufferProducer);
711}
712
713bool SurfaceFlinger::authenticateSurfaceTextureLocked(
714 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800715 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700716 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800717}
718
Brian Anderson6b376712017-04-04 10:51:39 -0700719status_t SurfaceFlinger::getSupportedFrameTimestamps(
720 std::vector<FrameEvent>* outSupported) const {
721 *outSupported = {
722 FrameEvent::REQUESTED_PRESENT,
723 FrameEvent::ACQUIRE,
724 FrameEvent::LATCH,
725 FrameEvent::FIRST_REFRESH_START,
726 FrameEvent::LAST_REFRESH_START,
727 FrameEvent::GPU_COMPOSITION_DONE,
728 FrameEvent::DEQUEUE_READY,
729 FrameEvent::RELEASE,
730 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700731 ConditionalLock _l(mStateLock,
732 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700733 if (!getHwComposer().hasCapability(
734 HWC2::Capability::PresentFenceIsNotReliable)) {
735 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
736 }
737 return NO_ERROR;
738}
739
Dan Stoza7f7da322014-05-02 15:26:25 -0700740status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
741 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700742 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700743 return BAD_VALUE;
744 }
745
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500746 if (!display.get())
747 return NAME_NOT_FOUND;
748
Jesse Hall692c7232012-11-08 15:41:56 -0800749 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700750 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800751 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700752 type = i;
753 break;
754 }
755 }
756
757 if (type < 0) {
758 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700759 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700760
Mathias Agopian8b736f12012-08-13 17:54:26 -0700761 // TODO: Not sure if display density should handled by SF any longer
762 class Density {
763 static int getDensityFromProperty(char const* propName) {
764 char property[PROPERTY_VALUE_MAX];
765 int density = 0;
766 if (property_get(propName, property, NULL) > 0) {
767 density = atoi(property);
768 }
769 return density;
770 }
771 public:
772 static int getEmuDensity() {
773 return getDensityFromProperty("qemu.sf.lcd_density"); }
774 static int getBuildDensity() {
775 return getDensityFromProperty("ro.sf.lcd_density"); }
776 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700777
Dan Stoza7f7da322014-05-02 15:26:25 -0700778 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700779
Steven Thomas6d8110b2017-08-31 18:24:21 -0700780 ConditionalLock _l(mStateLock,
781 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800782 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700783 DisplayInfo info = DisplayInfo();
784
Dan Stoza9e56aa02015-11-02 13:00:03 -0800785 float xdpi = hwConfig->getDpiX();
786 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700787
788 if (type == DisplayDevice::DISPLAY_PRIMARY) {
789 // The density of the device is provided by a build property
790 float density = Density::getBuildDensity() / 160.0f;
791 if (density == 0) {
792 // the build doesn't provide a density -- this is wrong!
793 // use xdpi instead
794 ALOGE("ro.sf.lcd_density must be defined as a build property");
795 density = xdpi / 160.0f;
796 }
797 if (Density::getEmuDensity()) {
798 // if "qemu.sf.lcd_density" is specified, it overrides everything
799 xdpi = ydpi = density = Density::getEmuDensity();
800 density /= 160.0f;
801 }
802 info.density = density;
803
804 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700805 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000806 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700807 } else {
808 // TODO: where should this value come from?
809 static const int TV_DENSITY = 213;
810 info.density = TV_DENSITY / 160.0f;
811 info.orientation = 0;
812 }
813
Dan Stoza9e56aa02015-11-02 13:00:03 -0800814 info.w = hwConfig->getWidth();
815 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700816 info.xdpi = xdpi;
817 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800818 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900819 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820
Andy McFadden91b2ca82014-06-13 14:04:23 -0700821 // This is how far in advance a buffer must be queued for
822 // presentation at a given time. If you want a buffer to appear
823 // on the screen at time N, you must submit the buffer before
824 // (N - presentationDeadline).
825 //
826 // Normally it's one full refresh period (to give SF a chance to
827 // latch the buffer), but this can be reduced by configuring a
828 // DispSync offset. Any additional delays introduced by the hardware
829 // composer or panel must be accounted for here.
830 //
831 // We add an additional 1ms to allow for processing time and
832 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800834 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700835
836 // All non-virtual displays are currently considered secure.
837 info.secure = true;
838
Michael Wright28f24d02016-07-12 13:30:53 -0700839 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 }
841
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 return NO_ERROR;
843}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700844
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800845status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700846 DisplayStatInfo* stats) {
847 if (stats == NULL) {
848 return BAD_VALUE;
849 }
850
851 // FIXME for now we always return stats for the primary display
852 memset(stats, 0, sizeof(*stats));
853 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
854 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
855 return NO_ERROR;
856}
857
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700858int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800859 if (display == NULL) {
860 ALOGE("%s : display is NULL", __func__);
861 return BAD_VALUE;
862 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700863
864 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700865 if (device != NULL) {
866 return device->getActiveConfig();
867 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700868
Dan Stoza24a42e92015-03-09 10:04:11 -0700869 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700870}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700871
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700872void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
873 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
874 this);
875 int32_t type = hw->getDisplayType();
876 int currentMode = hw->getActiveConfig();
877
878 if (mode == currentMode) {
879 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
880 return;
881 }
882
883 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
884 ALOGW("Trying to set config for virtual display");
885 return;
886 }
887
888 hw->setActiveConfig(mode);
889 getHwComposer().setActiveConfig(type, mode);
890}
891
892status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
893 class MessageSetActiveConfig: public MessageBase {
894 SurfaceFlinger& mFlinger;
895 sp<IBinder> mDisplay;
896 int mMode;
897 public:
898 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
899 int mode) :
900 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
901 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700902 Vector<DisplayInfo> configs;
903 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700904 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700905 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700906 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700907 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700908 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700909 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
910 if (hw == NULL) {
911 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700912 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700913 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
914 ALOGW("Attempt to set active config = %d for virtual display",
915 mMode);
916 } else {
917 mFlinger.setActiveConfigInternal(hw, mMode);
918 }
919 return true;
920 }
921 };
922 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
923 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700924 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700925}
Michael Wright28f24d02016-07-12 13:30:53 -0700926status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
927 Vector<android_color_mode_t>* outColorModes) {
928 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
929 return BAD_VALUE;
930 }
931
932 if (!display.get()) {
933 return NAME_NOT_FOUND;
934 }
935
936 int32_t type = NAME_NOT_FOUND;
937 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
938 if (display == mBuiltinDisplays[i]) {
939 type = i;
940 break;
941 }
942 }
943
944 if (type < 0) {
945 return type;
946 }
947
Steven Thomas6d8110b2017-08-31 18:24:21 -0700948 std::vector<android_color_mode_t> modes;
949 {
950 ConditionalLock _l(mStateLock,
951 std::this_thread::get_id() != mMainThreadId);
952 modes = getHwComposer().getColorModes(type);
953 }
Michael Wright28f24d02016-07-12 13:30:53 -0700954 outColorModes->clear();
955 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
956
957 return NO_ERROR;
958}
959
960android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700961 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700962 if (device != nullptr) {
963 return device->getActiveColorMode();
964 }
965 return static_cast<android_color_mode_t>(BAD_VALUE);
966}
967
968void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
969 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700970 int32_t type = hw->getDisplayType();
971 android_color_mode_t currentMode = hw->getActiveColorMode();
972
973 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700974 return;
975 }
976
977 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
978 ALOGW("Trying to set config for virtual display");
979 return;
980 }
981
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600982 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
983 hw->getDisplayType());
984
Michael Wright28f24d02016-07-12 13:30:53 -0700985 hw->setActiveColorMode(mode);
986 getHwComposer().setActiveColorMode(type, mode);
987}
988
989
990status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
991 android_color_mode_t colorMode) {
992 class MessageSetActiveColorMode: public MessageBase {
993 SurfaceFlinger& mFlinger;
994 sp<IBinder> mDisplay;
995 android_color_mode_t mMode;
996 public:
997 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
998 android_color_mode_t mode) :
999 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1000 virtual bool handler() {
1001 Vector<android_color_mode_t> modes;
1002 mFlinger.getDisplayColorModes(mDisplay, &modes);
1003 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1004 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001005 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1006 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001007 return true;
1008 }
1009 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1010 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001011 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1012 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001013 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001014 ALOGW("Attempt to set active color mode %s %d for virtual display",
1015 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001016 } else {
1017 mFlinger.setActiveColorModeInternal(hw, mMode);
1018 }
1019 return true;
1020 }
1021 };
1022 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1023 postMessageSync(msg);
1024 return NO_ERROR;
1025}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001026
Svetoslavd85084b2014-03-20 10:28:31 -07001027status_t SurfaceFlinger::clearAnimationFrameStats() {
1028 Mutex::Autolock _l(mStateLock);
1029 mAnimFrameTracker.clearStats();
1030 return NO_ERROR;
1031}
1032
1033status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1034 Mutex::Autolock _l(mStateLock);
1035 mAnimFrameTracker.getStats(outStats);
1036 return NO_ERROR;
1037}
1038
Dan Stozac4f471e2016-03-24 09:31:08 -07001039status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1040 HdrCapabilities* outCapabilities) const {
1041 Mutex::Autolock _l(mStateLock);
1042
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001043 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001044 if (displayDevice == nullptr) {
1045 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1046 return BAD_VALUE;
1047 }
1048
1049 std::unique_ptr<HdrCapabilities> capabilities =
1050 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1051 if (capabilities) {
1052 std::swap(*outCapabilities, *capabilities);
1053 } else {
1054 return BAD_VALUE;
1055 }
1056
1057 return NO_ERROR;
1058}
1059
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001060status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1061 if (enable == mInjectVSyncs) {
1062 return NO_ERROR;
1063 }
1064
1065 if (enable) {
1066 mInjectVSyncs = enable;
1067 ALOGV("VSync Injections enabled");
1068 if (mVSyncInjector.get() == nullptr) {
1069 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001070 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001071 }
1072 mEventQueue.setEventThread(mInjectorEventThread);
1073 } else {
1074 mInjectVSyncs = enable;
1075 ALOGV("VSync Injections disabled");
1076 mEventQueue.setEventThread(mSFEventThread);
1077 mVSyncInjector.clear();
1078 }
1079 return NO_ERROR;
1080}
1081
1082status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1083 if (!mInjectVSyncs) {
1084 ALOGE("VSync Injections not enabled");
1085 return BAD_VALUE;
1086 }
1087 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1088 ALOGV("Injecting VSync inside SurfaceFlinger");
1089 mVSyncInjector->onInjectSyncEvent(when);
1090 }
1091 return NO_ERROR;
1092}
1093
Kalle Raitaa099a242017-01-11 11:17:29 -08001094status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1095 IPCThreadState* ipc = IPCThreadState::self();
1096 const int pid = ipc->getCallingPid();
1097 const int uid = ipc->getCallingUid();
1098 if ((uid != AID_SHELL) &&
1099 !PermissionCache::checkPermission(sDump, pid, uid)) {
1100 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1101 return PERMISSION_DENIED;
1102 }
1103
1104 // Try to acquire a lock for 1s, fail gracefully
1105 const status_t err = mStateLock.timedLock(s2ns(1));
1106 const bool locked = (err == NO_ERROR);
1107 if (!locked) {
1108 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1109 return TIMED_OUT;
1110 }
1111
1112 outLayers->clear();
1113 mCurrentState.traverseInZOrder([&](Layer* layer) {
1114 outLayers->push_back(layer->getLayerDebugInfo());
1115 });
1116
1117 mStateLock.unlock();
1118 return NO_ERROR;
1119}
1120
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001121// ----------------------------------------------------------------------------
1122
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001123sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1124 ISurfaceComposer::VsyncSource vsyncSource) {
1125 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1126 return mSFEventThread->createEventConnection();
1127 } else {
1128 return mEventThread->createEventConnection();
1129 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001130}
1131
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001132// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001133
1134void SurfaceFlinger::waitForEvent() {
1135 mEventQueue.waitMessage();
1136}
1137
1138void SurfaceFlinger::signalTransaction() {
1139 mEventQueue.invalidate();
1140}
1141
1142void SurfaceFlinger::signalLayerUpdate() {
1143 mEventQueue.invalidate();
1144}
1145
1146void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001147 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001148 mEventQueue.refresh();
1149}
1150
1151status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001152 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001153 return mEventQueue.postMessage(msg, reltime);
1154}
1155
1156status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001157 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001158 status_t res = mEventQueue.postMessage(msg, reltime);
1159 if (res == NO_ERROR) {
1160 msg->wait();
1161 }
1162 return res;
1163}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001164
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001165void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001166 do {
1167 waitForEvent();
1168 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001169}
1170
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001171void SurfaceFlinger::enableHardwareVsync() {
1172 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001173 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001174 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001175 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1176 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001177 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001178 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001179}
1180
Jesse Hall948fe0c2013-10-14 12:56:09 -07001181void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001182 Mutex::Autolock _l(mHWVsyncLock);
1183
Jesse Hall948fe0c2013-10-14 12:56:09 -07001184 if (makeAvailable) {
1185 mHWVsyncAvailable = true;
1186 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001187 // Hardware vsync is not currently available, so abort the resync
1188 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001189 return;
1190 }
1191
Dan Stoza9e56aa02015-11-02 13:00:03 -08001192 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1193 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194
1195 mPrimaryDispSync.reset();
1196 mPrimaryDispSync.setPeriod(period);
1197
1198 if (!mPrimaryHWVsyncEnabled) {
1199 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001200 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1201 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001202 mPrimaryHWVsyncEnabled = true;
1203 }
1204}
1205
Jesse Hall948fe0c2013-10-14 12:56:09 -07001206void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001207 Mutex::Autolock _l(mHWVsyncLock);
1208 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001209 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1210 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001211 mPrimaryDispSync.endResync();
1212 mPrimaryHWVsyncEnabled = false;
1213 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001214 if (makeUnavailable) {
1215 mHWVsyncAvailable = false;
1216 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217}
1218
Tim Murray4a4e4a22016-04-19 16:29:23 +00001219void SurfaceFlinger::resyncWithRateLimit() {
1220 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001221
1222 // No explicit locking is needed here since EventThread holds a lock while calling this method
1223 static nsecs_t sLastResyncAttempted = 0;
1224 const nsecs_t now = systemTime();
1225 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001226 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001227 }
Dan Stoza57164302017-05-08 14:03:54 -07001228 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001229}
1230
Steven Thomasb02664d2017-07-26 18:48:28 -07001231void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1232 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001233 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001234 // Ignore any vsyncs from a previous hardware composer.
1235 if (sequenceId != mComposerSequenceId) {
1236 return;
1237 }
1238
1239 int32_t type;
1240 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001241 return;
1242 }
1243
Jamie Gennisd1700752013-10-14 12:22:52 -07001244 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245
Jamie Gennisd1700752013-10-14 12:22:52 -07001246 { // Scope for the lock
1247 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001248 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001249 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001250 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001251 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001252
1253 if (needsHwVsync) {
1254 enableHardwareVsync();
1255 } else {
1256 disableHardwareVsync(false);
1257 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001258}
1259
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001260void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001261 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001262 *compositorTiming = mCompositorTiming;
1263}
1264
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001265void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001266 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001267 wp<IBinder> token = mBuiltinDisplays[type];
1268
1269 // All non-virtual displays are currently considered secure.
1270 const bool isSecure = true;
1271
1272 sp<IGraphicBufferProducer> producer;
1273 sp<IGraphicBufferConsumer> consumer;
1274 BufferQueue::createBufferQueue(&producer, &consumer);
1275
1276 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1277
1278 bool hasWideColorModes = false;
1279 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1280 for (android_color_mode_t colorMode : modes) {
1281 switch (colorMode) {
1282 case HAL_COLOR_MODE_DISPLAY_P3:
1283 case HAL_COLOR_MODE_ADOBE_RGB:
1284 case HAL_COLOR_MODE_DCI_P3:
1285 hasWideColorModes = true;
1286 break;
1287 default:
1288 break;
1289 }
1290 }
1291 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1292 token, fbs, producer, mRenderEngine->getEGLConfig(),
1293 hasWideColorModes && hasWideColorDisplay);
1294 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001295 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1296 if (hasWideColorModes && hasWideColorDisplay) {
1297 defaultColorMode = HAL_COLOR_MODE_SRGB;
1298 }
1299 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001300 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001301
1302 // Add the primary display token to mDrawingState so we don't try to
1303 // recreate the DisplayDevice for the primary display.
1304 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1305
1306 // make the GLContext current so that we can create textures when creating
1307 // Layers (which may happens before we render something)
1308 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001309}
1310
Steven Thomasb02664d2017-07-26 18:48:28 -07001311void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1312 hwc2_display_t display, HWC2::Connection connection,
1313 bool primaryDisplay) {
1314 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1315 sequenceId, display,
1316 connection == HWC2::Connection::Connected ?
1317 "connected" : "disconnected",
1318 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001319
Steven Thomasb02664d2017-07-26 18:48:28 -07001320 // Only lock if we're not on the main thread. This function is normally
1321 // called on a hwbinder thread, but for the primary display it's called on
1322 // the main thread with the state lock already held, so don't attempt to
1323 // acquire it here.
1324 ConditionalLock lock(mStateLock,
1325 std::this_thread::get_id() != mMainThreadId);
1326
1327 if (primaryDisplay) {
1328 mHwc->onHotplug(display, connection);
1329 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1330 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001331 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001332 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001333 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001334 if (sequenceId != mComposerSequenceId) {
1335 return;
1336 }
1337 if (mHwc->isUsingVrComposer()) {
1338 ALOGE("External displays are not supported by the vr hardware composer.");
1339 return;
1340 }
1341 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001342 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001344 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001345 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001346 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1347 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001348 }
1349 setTransactionFlags(eDisplayTransactionNeeded);
1350
Andy McFadden9e9689c2012-10-10 18:17:51 -07001351 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001352 }
Mathias Agopian86303202012-07-24 22:46:10 -07001353}
1354
Steven Thomasb02664d2017-07-26 18:48:28 -07001355void SurfaceFlinger::onRefreshReceived(int sequenceId,
1356 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001357 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 if (sequenceId != mComposerSequenceId) {
1359 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001360 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001361 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001362}
1363
Dan Stoza9e56aa02015-11-02 13:00:03 -08001364void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001365 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001366 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001367 getHwComposer().setVsyncEnabled(disp,
1368 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001369}
1370
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001371// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001372void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001373 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001374 // Clear the drawing state so that the logic inside of
1375 // handleTransactionLocked will fire. It will determine the delta between
1376 // mCurrentState and mDrawingState and re-apply all changes when we make the
1377 // transition.
1378 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001380 mDisplays.clear();
1381}
1382
Steven Thomas050b2c82017-03-06 11:45:16 -08001383void SurfaceFlinger::updateVrFlinger() {
1384 if (!mVrFlinger)
1385 return;
1386 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1387 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001388 return;
1389 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001390
Steven Thomasb02664d2017-07-26 18:48:28 -07001391 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1392 ALOGE("Vr flinger is only supported for remote hardware composer"
1393 " service connections. Ignoring request to transition to vr"
1394 " flinger.");
1395 mVrFlingerRequestsDisplay = false;
1396 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001397 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001398
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001400
Steven Thomasb02664d2017-07-26 18:48:28 -07001401 int currentDisplayPowerMode = getDisplayDeviceLocked(
1402 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403
Steven Thomasb02664d2017-07-26 18:48:28 -07001404 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001405 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001406 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 resetDisplayState();
1409 mHwc.reset(); // Delete the current instance before creating the new one
1410 mHwc.reset(new HWComposer(
1411 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1412 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001413
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1415 "Switched to non-remote hardware composer");
1416
1417 if (vrFlingerRequestsDisplay) {
1418 mVrFlinger->GrantDisplayOwnership();
1419 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001421 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001422
1423 mVisibleRegionsDirty = true;
1424 invalidateHwcGeometry();
1425
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001426 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1428 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1429 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001430
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 // Reset the timing values to account for the period of the swapped in HWC
1432 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1433 const nsecs_t period = activeConfig->getVsyncPeriod();
1434 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001435
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 // Use phase of 0 since phase is not known.
1437 // Use latency of 0, which will snap to the ideal latency.
1438 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001439
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001440 android_atomic_or(1, &mRepaintEverything);
1441 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001442}
1443
Mathias Agopian4fec8732012-06-29 14:12:52 -07001444void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001445 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001446 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001447 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001448 bool frameMissed = !mHadClientComposition &&
1449 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001450 (mPreviousPresentFence->getSignalTime() ==
1451 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001452 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001453 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001454 signalLayerUpdate();
1455 break;
1456 }
1457
Steven Thomas050b2c82017-03-06 11:45:16 -08001458 // Now that we're going to make it to the handleMessageTransaction()
1459 // call below it's safe to call updateVrFlinger(), which will
1460 // potentially trigger a display handoff.
1461 updateVrFlinger();
1462
Dan Stoza6b9454d2014-11-07 16:00:59 -08001463 bool refreshNeeded = handleMessageTransaction();
1464 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001465 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001467 // Signal a refresh if a transaction modified the window state,
1468 // a new buffer was latched, or if HWC has requested a full
1469 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001470 signalRefresh();
1471 }
1472 break;
1473 }
1474 case MessageQueue::REFRESH: {
1475 handleMessageRefresh();
1476 break;
1477 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001478 }
1479}
1480
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001482 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001483 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001484 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001485 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001486 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001487 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001488}
1489
Dan Stoza6b9454d2014-11-07 16:00:59 -08001490bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001491 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001492 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001493}
1494
1495void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001496 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001497
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001498 mRefreshPending = false;
1499
Pablo Ceballos40845df2016-01-25 17:41:15 -08001500 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001501
Brian Andersond6927fb2016-07-23 23:37:30 -07001502 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001503 rebuildLayerStacks();
1504 setUpHWComposer();
1505 doDebugFlashRegions();
1506 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001507 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001508
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001509 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001510
1511 mHadClientComposition = false;
1512 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1513 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1514 mHadClientComposition = mHadClientComposition ||
1515 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1516 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001517
Dan Stoza9e56aa02015-11-02 13:00:03 -08001518 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001520
Mathias Agopiancd60f992012-08-16 16:28:27 -07001521void SurfaceFlinger::doDebugFlashRegions()
1522{
1523 // is debugging enabled
1524 if (CC_LIKELY(!mDebugRegion))
1525 return;
1526
1527 const bool repaintEverything = mRepaintEverything;
1528 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1529 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001530 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001531 // transform the dirty region into this screen's coordinate space
1532 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1533 if (!dirtyRegion.isEmpty()) {
1534 // redraw the whole screen
1535 doComposeSurfaces(hw, Region(hw->bounds()));
1536
1537 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001538 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001539 RenderEngine& engine(getRenderEngine());
1540 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1541
Mathias Agopianda27af92012-09-13 18:17:13 -07001542 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001543 }
1544 }
1545 }
1546
1547 postFramebuffer();
1548
1549 if (mDebugRegion > 1) {
1550 usleep(mDebugRegion * 1000);
1551 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001552
Dan Stoza9e56aa02015-11-02 13:00:03 -08001553 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001554 auto& displayDevice = mDisplays[displayId];
1555 if (!displayDevice->isDisplayOn()) {
1556 continue;
1557 }
1558
1559 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001560 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1561 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001562 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001563}
1564
Brian Andersond6927fb2016-07-23 23:37:30 -07001565void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001567 ATRACE_CALL();
1568 ALOGV("preComposition");
1569
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001571 mDrawingState.traverseInZOrder([&](Layer* layer) {
1572 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001573 needExtraInvalidate = true;
1574 }
Robert Carr2047fae2016-11-28 14:09:09 -08001575 });
1576
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577 if (needExtraInvalidate) {
1578 signalLayerUpdate();
1579 }
1580}
1581
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001582void SurfaceFlinger::updateCompositorTiming(
1583 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1584 std::shared_ptr<FenceTime>& presentFenceTime) {
1585 // Update queue of past composite+present times and determine the
1586 // most recently known composite to present latency.
1587 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1588 nsecs_t compositeToPresentLatency = -1;
1589 while (!mCompositePresentTimes.empty()) {
1590 CompositePresentTime& cpt = mCompositePresentTimes.front();
1591 // Cached values should have been updated before calling this method,
1592 // which helps avoid duplicate syscalls.
1593 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1594 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1595 break;
1596 }
1597 compositeToPresentLatency = displayTime - cpt.composite;
1598 mCompositePresentTimes.pop();
1599 }
1600
1601 // Don't let mCompositePresentTimes grow unbounded, just in case.
1602 while (mCompositePresentTimes.size() > 16) {
1603 mCompositePresentTimes.pop();
1604 }
1605
Brian Andersond0010582017-03-07 13:20:31 -08001606 setCompositorTimingSnapped(
1607 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1608}
1609
1610void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1611 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001612 // Integer division and modulo round toward 0 not -inf, so we need to
1613 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001614 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001615 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1616 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1617
Brian Andersond0010582017-03-07 13:20:31 -08001618 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1619 if (idealLatency <= 0) {
1620 idealLatency = vsyncInterval;
1621 }
1622
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001623 // Snap the latency to a value that removes scheduling jitter from the
1624 // composition and present times, which often have >1ms of jitter.
1625 // Reducing jitter is important if an app attempts to extrapolate
1626 // something (such as user input) to an accurate diasplay time.
1627 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1628 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001629 nsecs_t bias = vsyncInterval / 2;
1630 int64_t extraVsyncs =
1631 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1632 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1633 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634
Brian Andersond0010582017-03-07 13:20:31 -08001635 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001636 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1637 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001638 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001639}
1640
1641void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001642{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001643 ATRACE_CALL();
1644 ALOGV("postComposition");
1645
Brian Anderson3546a3f2016-07-14 11:51:14 -07001646 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001647 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001648 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001649 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001650 }
1651
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001652 // |mStateLock| not needed as we are on the main thread
1653 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001654
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001655 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001656 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1657 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1658 glCompositionDoneFenceTime =
1659 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1660 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1661 } else {
1662 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1663 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001664
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001665 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001666 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1667 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1668 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001669
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001670 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1671 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1672
1673 // We use the refreshStartTime which might be sampled a little later than
1674 // when we started doing work for this frame, but that should be okay
1675 // since updateCompositorTiming has snapping logic.
1676 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001677 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001678 CompositorTiming compositorTiming;
1679 {
1680 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1681 compositorTiming = mCompositorTiming;
1682 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001683
Robert Carr2047fae2016-11-28 14:09:09 -08001684 mDrawingState.traverseInZOrder([&](Layer* layer) {
1685 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001686 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001687 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001688 recordBufferingStats(layer->getName().string(),
1689 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001690 }
Robert Carr2047fae2016-11-28 14:09:09 -08001691 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001692
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001693 if (presentFenceTime->isValid()) {
1694 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001695 enableHardwareVsync();
1696 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001697 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001698 }
1699 }
1700
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001701 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001702 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001703 enableHardwareVsync();
1704 }
1705 }
1706
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001707 if (mAnimCompositionPending) {
1708 mAnimCompositionPending = false;
1709
Brian Anderson4e606e32017-03-16 15:34:57 -07001710 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001711 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001712 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001713 } else {
1714 // The HWC doesn't support present fences, so use the refresh
1715 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001716 nsecs_t presentTime =
1717 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001718 mAnimFrameTracker.setActualPresentTime(presentTime);
1719 }
1720 mAnimFrameTracker.advanceFrame();
1721 }
Dan Stozab90cf072015-03-05 11:05:59 -08001722
1723 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1724 return;
1725 }
1726
1727 nsecs_t currentTime = systemTime();
1728 if (mHasPoweredOff) {
1729 mHasPoweredOff = false;
1730 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001731 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001732 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001733 if (numPeriods < NUM_BUCKETS - 1) {
1734 mFrameBuckets[numPeriods] += elapsedTime;
1735 } else {
1736 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1737 }
1738 mTotalTime += elapsedTime;
1739 }
1740 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001741}
1742
1743void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001744 ATRACE_CALL();
1745 ALOGV("rebuildLayerStacks");
1746
Mathias Agopiancd60f992012-08-16 16:28:27 -07001747 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001748 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001749 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001750 mVisibleRegionsDirty = false;
1751 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001752
Jeff Sharkey76488112017-02-27 14:15:18 -07001753 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1754 Region opaqueRegion;
1755 Region dirtyRegion;
1756 Vector<sp<Layer>> layersSortedByZ;
1757 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1758 const Transform& tr(displayDevice->getTransform());
1759 const Rect bounds(displayDevice->getBounds());
1760 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001761 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001762
Jeff Sharkey76488112017-02-27 14:15:18 -07001763 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001764 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1765 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001766 Region drawRegion(tr.transform(
1767 layer->visibleNonTransparentRegion));
1768 drawRegion.andSelf(bounds);
1769 if (!drawRegion.isEmpty()) {
1770 layersSortedByZ.add(layer);
1771 } else {
1772 // Clear out the HWC layer if this layer was
1773 // previously visible, but no longer is
Steven Thomasb02664d2017-07-26 18:48:28 -07001774 layer->destroyHwcLayer(
1775 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001776 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001777 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001778 // WM changes displayDevice->layerStack upon sleep/awake.
1779 // Here we make sure we delete the HWC layers even if
1780 // WM changed their layer stack.
Steven Thomasb02664d2017-07-26 18:48:28 -07001781 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001782 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001783 });
1784 }
1785 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1786 displayDevice->undefinedRegion.set(bounds);
1787 displayDevice->undefinedRegion.subtractSelf(
1788 tr.transform(opaqueRegion));
1789 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001790 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001791 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001792}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001793
Romain Guy0147a172017-06-01 13:53:56 -07001794mat4 SurfaceFlinger::computeSaturationMatrix() const {
1795 if (mSaturation == 1.0f) {
1796 return mat4();
1797 }
1798
1799 // Rec.709 luma coefficients
1800 float3 luminance{0.213f, 0.715f, 0.072f};
1801 luminance *= 1.0f - mSaturation;
1802 return mat4(
1803 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1804 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1805 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1806 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1807 );
1808}
1809
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001810// pickColorMode translates a given dataspace into the best available color mode.
1811// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001812android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001813 switch (dataSpace) {
1814 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1815 // system expects.
1816 case HAL_DATASPACE_UNKNOWN:
1817 case HAL_DATASPACE_SRGB:
1818 case HAL_DATASPACE_V0_SRGB:
1819 return HAL_COLOR_MODE_SRGB;
1820 break;
1821
1822 case HAL_DATASPACE_DISPLAY_P3:
1823 return HAL_COLOR_MODE_DISPLAY_P3;
1824 break;
1825
1826 default:
1827 // TODO (courtneygo): Do we want to assert an error here?
1828 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1829 dataSpace);
1830 return HAL_COLOR_MODE_SRGB;
1831 break;
1832 }
1833}
1834
Romain Guy0147a172017-06-01 13:53:56 -07001835android_dataspace SurfaceFlinger::bestTargetDataSpace(
1836 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001837 // Only support sRGB and Display-P3 right now.
1838 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1839 return HAL_DATASPACE_DISPLAY_P3;
1840 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001841 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1842 return HAL_DATASPACE_DISPLAY_P3;
1843 }
1844 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1845 return HAL_DATASPACE_DISPLAY_P3;
1846 }
1847
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001848 return HAL_DATASPACE_V0_SRGB;
1849}
1850
Mathias Agopiancd60f992012-08-16 16:28:27 -07001851void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001852 ATRACE_CALL();
1853 ALOGV("setUpHWComposer");
1854
Jesse Hall028dc8f2013-08-20 16:35:32 -07001855 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001856 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1857 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1858 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1859
1860 // If nothing has changed (!dirty), don't recompose.
1861 // If something changed, but we don't currently have any visible layers,
1862 // and didn't when we last did a composition, then skip it this time.
1863 // The second rule does two things:
1864 // - When all layers are removed from a display, we'll emit one black
1865 // frame, then nothing more until we get new layers.
1866 // - When a display is created with a private layer stack, we won't
1867 // emit any black frames until a layer is added to the layer stack.
1868 bool mustRecompose = dirty && !(empty && wasEmpty);
1869
1870 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1871 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1872 mustRecompose ? "doing" : "skipping",
1873 dirty ? "+" : "-",
1874 empty ? "+" : "-",
1875 wasEmpty ? "+" : "-");
1876
Dan Stoza71433162014-02-04 16:22:36 -08001877 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001878
1879 if (mustRecompose) {
1880 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1881 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001882 }
1883
Dan Stoza9e56aa02015-11-02 13:00:03 -08001884 // build the h/w work list
1885 if (CC_UNLIKELY(mGeometryInvalid)) {
1886 mGeometryInvalid = false;
1887 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1888 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1889 const auto hwcId = displayDevice->getHwcDisplayId();
1890 if (hwcId >= 0) {
1891 const Vector<sp<Layer>>& currentLayers(
1892 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001893 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001894 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001895 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001896 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001898 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001899 }
1900 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001901
Robert Carrae060832016-11-28 10:51:00 -08001902 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001903 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001904 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001905 }
1906 }
1907 }
1908 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001909 }
Riley Andrews03414a12014-07-01 14:22:59 -07001910
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001911
Romain Guy0147a172017-06-01 13:53:56 -07001912 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001913
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 // Set the per-frame data
1915 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1916 auto& displayDevice = mDisplays[displayId];
1917 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001918
Dan Stoza9e56aa02015-11-02 13:00:03 -08001919 if (hwcId < 0) {
1920 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001921 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001922 if (colorMatrix != mPreviousColorMatrix) {
1923 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1924 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1925 "display %zd: %d", displayId, result);
1926 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001927 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1928 layer->setPerFrameData(displayDevice);
1929 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001930
1931 if (hasWideColorDisplay) {
1932 android_color_mode newColorMode;
1933 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1934
1935 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1936 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1937 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1938 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1939 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1940 }
1941 newColorMode = pickColorMode(newDataSpace);
1942
Thierry Strudel2924d012017-08-14 15:19:37 -07001943 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001944 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001945 }
1946
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001947 mPreviousColorMatrix = colorMatrix;
1948
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001950 auto& displayDevice = mDisplays[displayId];
1951 if (!displayDevice->isDisplayOn()) {
1952 continue;
1953 }
1954
1955 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1957 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001958 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001959}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001960
Mathias Agopiancd60f992012-08-16 16:28:27 -07001961void SurfaceFlinger::doComposition() {
1962 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001963 ALOGV("doComposition");
1964
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001965 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001966 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001967 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001968 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001969 // transform the dirty region into this screen's coordinate space
1970 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001971
1972 // repaint the framebuffer (if needed)
1973 doDisplayComposition(hw, dirtyRegion);
1974
Mathias Agopiancd60f992012-08-16 16:28:27 -07001975 hw->dirtyRegion.clear();
1976 hw->flip(hw->swapRegion);
1977 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001978 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001979 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001980 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001981}
1982
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001983void SurfaceFlinger::postFramebuffer()
1984{
Mathias Agopian841cde52012-03-01 15:44:37 -08001985 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001986 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001987
Mathias Agopiana44b0412011-10-16 18:46:35 -07001988 const nsecs_t now = systemTime();
1989 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001990
Dan Stoza9e56aa02015-11-02 13:00:03 -08001991 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1992 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001993 if (!displayDevice->isDisplayOn()) {
1994 continue;
1995 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001996 const auto hwcId = displayDevice->getHwcDisplayId();
1997 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001998 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001999 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002000 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002001 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2003 sp<Fence> releaseFence = Fence::NO_FENCE;
2004 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
2005 releaseFence = displayDevice->getClientTargetAcquireFence();
2006 } else {
2007 auto hwcLayer = layer->getHwcLayer(hwcId);
2008 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002009 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002010 layer->onLayerDisplayed(releaseFence);
2011 }
2012 if (hwcId >= 0) {
2013 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002014 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002015 }
2016
Mathias Agopiana44b0412011-10-16 18:46:35 -07002017 mLastSwapBufferTime = systemTime() - now;
2018 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002019
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002020 // |mStateLock| not needed as we are on the main thread
2021 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002022 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2023 logFrameStats();
2024 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002025}
2026
Mathias Agopian87baae12012-07-31 12:38:26 -07002027void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002028{
Mathias Agopian841cde52012-03-01 15:44:37 -08002029 ATRACE_CALL();
2030
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002031 // here we keep a copy of the drawing state (that is the state that's
2032 // going to be overwritten by handleTransactionLocked()) outside of
2033 // mStateLock so that the side-effects of the State assignment
2034 // don't happen with mStateLock held (which can cause deadlocks).
2035 State drawingState(mDrawingState);
2036
Mathias Agopianca4d3602011-05-19 15:38:14 -07002037 Mutex::Autolock _l(mStateLock);
2038 const nsecs_t now = systemTime();
2039 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002040
Mathias Agopianca4d3602011-05-19 15:38:14 -07002041 // Here we're guaranteed that some transaction flags are set
2042 // so we can call handleTransactionLocked() unconditionally.
2043 // We call getTransactionFlags(), which will also clear the flags,
2044 // with mStateLock held to guarantee that mCurrentState won't change
2045 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002046
Mathias Agopiane57f2922012-08-09 16:29:12 -07002047 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002048 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002049
Mathias Agopianca4d3602011-05-19 15:38:14 -07002050 mLastTransactionTime = systemTime() - now;
2051 mDebugInTransaction = 0;
2052 invalidateHwcGeometry();
2053 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002054}
2055
Mathias Agopian87baae12012-07-31 12:38:26 -07002056void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002057{
Dan Stoza7dde5992015-05-22 09:51:44 -07002058 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002059 mCurrentState.traverseInZOrder([](Layer* layer) {
2060 layer->notifyAvailableFrames();
2061 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002062
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002063 /*
2064 * Traversal of the children
2065 * (perform the transaction for each of them if needed)
2066 */
2067
Mathias Agopian3559b072012-08-15 13:46:03 -07002068 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002069 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002070 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002071 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002072
2073 const uint32_t flags = layer->doTransaction(0);
2074 if (flags & Layer::eVisibleRegion)
2075 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002076 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002077 }
2078
2079 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002080 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002081 */
2082
Mathias Agopiane57f2922012-08-09 16:29:12 -07002083 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002084 // here we take advantage of Vector's copy-on-write semantics to
2085 // improve performance by skipping the transaction entirely when
2086 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002087 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2088 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002089 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002090 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002091 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002092 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002093
2094 // find the displays that were removed
2095 // (ie: in drawing state but not in current state)
2096 // also handle displays that changed
2097 // (ie: displays that are in both lists)
2098 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002099 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2100 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002101 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002102 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002103 // Call makeCurrent() on the primary display so we can
2104 // be sure that nothing associated with this display
2105 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002106 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002107 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002108 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002109 if (hw != NULL)
2110 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002111 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002112 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002113 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002114 } else {
2115 ALOGW("trying to remove the main display");
2116 }
2117 } else {
2118 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002119 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002120 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002121 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2122 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002123 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002124 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002125 // recreating the DisplayDevice, so we just remove it
2126 // from the drawing state, so that it get re-added
2127 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002128 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002129 if (hw != NULL)
2130 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002131 mDisplays.removeItem(display);
2132 mDrawingState.displays.removeItemsAt(i);
2133 dc--; i--;
2134 // at this point we must loop to the next item
2135 continue;
2136 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002137
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002138 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002139 if (disp != NULL) {
2140 if (state.layerStack != draw[i].layerStack) {
2141 disp->setLayerStack(state.layerStack);
2142 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002143 if ((state.orientation != draw[i].orientation)
2144 || (state.viewport != draw[i].viewport)
2145 || (state.frame != draw[i].frame))
2146 {
2147 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002148 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002149 }
Michael Lentine47e45402014-07-18 15:34:25 -07002150 if (state.width != draw[i].width || state.height != draw[i].height) {
2151 disp->setDisplaySize(state.width, state.height);
2152 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002153 }
2154 }
2155 }
2156
2157 // find displays that were added
2158 // (ie: in current state but not in drawing state)
2159 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002160 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002161 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002162
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002163 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002164 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002165 sp<IGraphicBufferProducer> bqProducer;
2166 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002167 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002168
Dan Stoza9e56aa02015-11-02 13:00:03 -08002169 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002170 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002171 // Virtual displays without a surface are dormant:
2172 // they have external state (layer stack, projection,
2173 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002174 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002175
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002176 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002177 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002178 int width = 0;
2179 int status = state.surface->query(
2180 NATIVE_WINDOW_WIDTH, &width);
2181 ALOGE_IF(status != NO_ERROR,
2182 "Unable to query width (%d)", status);
2183 int height = 0;
2184 status = state.surface->query(
2185 NATIVE_WINDOW_HEIGHT, &height);
2186 ALOGE_IF(status != NO_ERROR,
2187 "Unable to query height (%d)", status);
2188 int intFormat = 0;
2189 status = state.surface->query(
2190 NATIVE_WINDOW_FORMAT, &intFormat);
2191 ALOGE_IF(status != NO_ERROR,
2192 "Unable to query format (%d)", status);
2193 auto format = static_cast<android_pixel_format_t>(
2194 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002195
Dan Stoza8cf150a2016-08-02 10:27:31 -07002196 mHwc->allocateVirtualDisplay(width, height, &format,
2197 &hwcId);
2198 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002199
Dan Stoza5cf424b2016-05-20 14:02:39 -07002200 // TODO: Plumb requested format back up to consumer
2201
Dan Stoza9e56aa02015-11-02 13:00:03 -08002202 sp<VirtualDisplaySurface> vds =
2203 new VirtualDisplaySurface(*mHwc,
2204 hwcId, state.surface, bqProducer,
2205 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002206
2207 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002208 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002209 }
2210 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002211 ALOGE_IF(state.surface!=NULL,
2212 "adding a supported display, but rendering "
2213 "surface is provided (%p), ignoring it",
2214 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002215
2216 hwcId = state.type;
2217 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2218 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002219 }
2220
2221 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002222 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002223 sp<DisplayDevice> hw =
2224 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2225 dispSurface, producer,
2226 mRenderEngine->getEGLConfig(),
2227 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002228 hw->setLayerStack(state.layerStack);
2229 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002230 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002231 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002232 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002233 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002234 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002235 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002236 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002237 }
2238 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002239 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002240 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002241
Mathias Agopian84300952012-11-21 16:02:13 -08002242 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2243 // The transform hint might have changed for some layers
2244 // (either because a display has changed, or because a layer
2245 // as changed).
2246 //
2247 // Walk through all the layers in currentLayers,
2248 // and update their transform hint.
2249 //
2250 // If a layer is visible only on a single display, then that
2251 // display is used to calculate the hint, otherwise we use the
2252 // default display.
2253 //
2254 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2255 // the hint is set before we acquire a buffer from the surface texture.
2256 //
2257 // NOTE: layer transactions have taken place already, so we use their
2258 // drawing state. However, SurfaceFlinger's own transaction has not
2259 // happened yet, so we must use the current state layer list
2260 // (soon to become the drawing state list).
2261 //
2262 sp<const DisplayDevice> disp;
2263 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002264 bool first = true;
2265 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002266 // NOTE: we rely on the fact that layers are sorted by
2267 // layerStack first (so we don't have to traverse the list
2268 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002269 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002270 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002271 currentlayerStack = layerStack;
2272 // figure out if this layerstack is mirrored
2273 // (more than one display) if so, pick the default display,
2274 // if not, pick the only display it's on.
2275 disp.clear();
2276 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2277 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002278 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002279 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002280 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002281 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002282 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002283 break;
2284 }
2285 }
2286 }
2287 }
Chet Haase91d25932013-04-11 15:24:55 -07002288 if (disp == NULL) {
2289 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2290 // redraw after transform hint changes. See bug 8508397.
2291
2292 // could be null when this layer is using a layerStack
2293 // that is not visible on any display. Also can occur at
2294 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002295 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002296 }
Chet Haase91d25932013-04-11 15:24:55 -07002297 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002298
2299 first = false;
2300 });
Mathias Agopian84300952012-11-21 16:02:13 -08002301 }
2302
2303
Mathias Agopian3559b072012-08-15 13:46:03 -07002304 /*
2305 * Perform our own transaction if needed
2306 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002307
2308 if (mLayersAdded) {
2309 mLayersAdded = false;
2310 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002311 mVisibleRegionsDirty = true;
2312 }
2313
2314 // some layers might have been removed, so
2315 // we need to update the regions they're exposing.
2316 if (mLayersRemoved) {
2317 mLayersRemoved = false;
2318 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002319 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002320 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002321 // this layer is not visible anymore
2322 // TODO: we could traverse the tree from front to back and
2323 // compute the actual visible region
2324 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002325 Region visibleReg;
2326 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002327 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002328 }
Robert Carr2047fae2016-11-28 14:09:09 -08002329 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002330 }
2331
2332 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002333
2334 updateCursorAsync();
2335}
2336
2337void SurfaceFlinger::updateCursorAsync()
2338{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002339 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2340 auto& displayDevice = mDisplays[displayId];
2341 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002342 continue;
2343 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002344
2345 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2346 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002347 }
2348 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002349}
2350
2351void SurfaceFlinger::commitTransaction()
2352{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002353 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002354 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002355 for (const auto& l : mLayersPendingRemoval) {
2356 recordBufferingStats(l->getName().string(),
2357 l->getOccupancyHistory(true));
2358 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002359 }
2360 mLayersPendingRemoval.clear();
2361 }
2362
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002363 // If this transaction is part of a window animation then the next frame
2364 // we composite should be considered an animation as well.
2365 mAnimCompositionPending = mAnimTransactionPending;
2366
Mathias Agopian4fec8732012-06-29 14:12:52 -07002367 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002368 mDrawingState.traverseInZOrder([](Layer* layer) {
2369 layer->commitChildList();
2370 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002371 mTransactionPending = false;
2372 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002373 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002374}
2375
Chia-I Wuab0c3192017-08-01 11:29:00 -07002376void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002377 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002378{
Mathias Agopian841cde52012-03-01 15:44:37 -08002379 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002380 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002381
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002382 Region aboveOpaqueLayers;
2383 Region aboveCoveredLayers;
2384 Region dirty;
2385
Mathias Agopian87baae12012-07-31 12:38:26 -07002386 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002387
Robert Carr2047fae2016-11-28 14:09:09 -08002388 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002389 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002390 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002391
Jesse Hall01e29052013-02-19 16:13:35 -08002392 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002393 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002394 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002395
Mathias Agopianab028732010-03-16 16:41:46 -07002396 /*
2397 * opaqueRegion: area of a surface that is fully opaque.
2398 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002399 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002400
2401 /*
2402 * visibleRegion: area of a surface that is visible on screen
2403 * and not fully transparent. This is essentially the layer's
2404 * footprint minus the opaque regions above it.
2405 * Areas covered by a translucent surface are considered visible.
2406 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002407 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002408
2409 /*
2410 * coveredRegion: area of a surface that is covered by all
2411 * visible regions above it (which includes the translucent areas).
2412 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002413 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002414
Jesse Halla8026d22012-09-25 13:25:04 -07002415 /*
2416 * transparentRegion: area of a surface that is hinted to be completely
2417 * transparent. This is only used to tell when the layer has no visible
2418 * non-transparent regions and can be removed from the layer list. It
2419 * does not affect the visibleRegion of this layer or any layers
2420 * beneath it. The hint may not be correct if apps don't respect the
2421 * SurfaceView restrictions (which, sadly, some don't).
2422 */
2423 Region transparentRegion;
2424
Mathias Agopianab028732010-03-16 16:41:46 -07002425
2426 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002427 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002428 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002429 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002430 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002431 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002432 if (!visibleRegion.isEmpty()) {
2433 // Remove the transparent area from the visible region
2434 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002435 if (tr.preserveRects()) {
2436 // transform the transparent region
2437 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002438 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002439 // transformation too complex, can't do the
2440 // transparent region optimization.
2441 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002442 }
Mathias Agopianab028732010-03-16 16:41:46 -07002443 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002444
Mathias Agopianab028732010-03-16 16:41:46 -07002445 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002446 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002447 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002448 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2449 // the opaque region is the layer's footprint
2450 opaqueRegion = visibleRegion;
2451 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452 }
2453 }
2454
Mathias Agopianab028732010-03-16 16:41:46 -07002455 // Clip the covered region to the visible region
2456 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2457
2458 // Update aboveCoveredLayers for next (lower) layer
2459 aboveCoveredLayers.orSelf(visibleRegion);
2460
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002461 // subtract the opaque region covered by the layers above us
2462 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463
2464 // compute this layer's dirty region
2465 if (layer->contentDirty) {
2466 // we need to invalidate the whole region
2467 dirty = visibleRegion;
2468 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002469 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002470 layer->contentDirty = false;
2471 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002472 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002473 * the exposed region consists of two components:
2474 * 1) what's VISIBLE now and was COVERED before
2475 * 2) what's EXPOSED now less what was EXPOSED before
2476 *
2477 * note that (1) is conservative, we start with the whole
2478 * visible region but only keep what used to be covered by
2479 * something -- which mean it may have been exposed.
2480 *
2481 * (2) handles areas that were not covered by anything but got
2482 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002483 */
Mathias Agopianab028732010-03-16 16:41:46 -07002484 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002485 const Region oldVisibleRegion = layer->visibleRegion;
2486 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002487 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2488 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489 }
2490 dirty.subtractSelf(aboveOpaqueLayers);
2491
2492 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002493 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494
Mathias Agopianab028732010-03-16 16:41:46 -07002495 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002497
Jesse Halla8026d22012-09-25 13:25:04 -07002498 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499 layer->setVisibleRegion(visibleRegion);
2500 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002501 layer->setVisibleNonTransparentRegion(
2502 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002503 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504
Mathias Agopian87baae12012-07-31 12:38:26 -07002505 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506}
2507
Chia-I Wuab0c3192017-08-01 11:29:00 -07002508void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002509 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002510 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002511 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002512 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002513 }
2514 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002515}
2516
Dan Stoza6b9454d2014-11-07 16:00:59 -08002517bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002519 ALOGV("handlePageFlip");
2520
Brian Andersond6927fb2016-07-23 23:37:30 -07002521 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002522
Mathias Agopian4fec8732012-06-29 14:12:52 -07002523 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002524 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002525 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002526
2527 // Store the set of layers that need updates. This set must not change as
2528 // buffers are being latched, as this could result in a deadlock.
2529 // Example: Two producers share the same command stream and:
2530 // 1.) Layer 0 is latched
2531 // 2.) Layer 0 gets a new frame
2532 // 2.) Layer 1 gets a new frame
2533 // 3.) Layer 1 is latched.
2534 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2535 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002536 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002537 if (layer->hasQueuedFrame()) {
2538 frameQueued = true;
2539 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002540 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002541 } else {
2542 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002543 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002544 } else {
2545 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002546 }
Robert Carr2047fae2016-11-28 14:09:09 -08002547 });
2548
Dan Stoza9e56aa02015-11-02 13:00:03 -08002549 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002550 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002551 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002552 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002553 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002554 newDataLatched = true;
2555 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002556 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002557
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002558 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002559
2560 // If we will need to wake up at some time in the future to deal with a
2561 // queued frame that shouldn't be displayed during this vsync period, wake
2562 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002563 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002564 signalLayerUpdate();
2565 }
2566
2567 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002568 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569}
2570
Mathias Agopianad456f92011-01-13 17:53:01 -08002571void SurfaceFlinger::invalidateHwcGeometry()
2572{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002573 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002574}
2575
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002576
Fabien Sanglard830b8472016-11-30 16:35:58 -08002577void SurfaceFlinger::doDisplayComposition(
2578 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002579 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580{
Dan Stoza71433162014-02-04 16:22:36 -08002581 // We only need to actually compose the display if:
2582 // 1) It is being handled by hardware composer, which may need this to
2583 // keep its virtual display state machine in sync, or
2584 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002585 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002586 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002587 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002588 return;
2589 }
2590
Dan Stoza9e56aa02015-11-02 13:00:03 -08002591 ALOGV("doDisplayComposition");
2592
Mathias Agopian87baae12012-07-31 12:38:26 -07002593 Region dirtyRegion(inDirtyRegion);
2594
Mathias Agopianb8a55602009-06-26 19:06:36 -07002595 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002596 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597
Fabien Sanglard830b8472016-11-30 16:35:58 -08002598 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002599 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002600 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2601 // takes a rectangle, we must make sure to update that whole
2602 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002603 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002604 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002605 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002606 // We need to redraw the rectangle that will be updated
2607 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002608 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002609 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002610 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002611 } else {
2612 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002613 dirtyRegion.set(displayDevice->bounds());
2614 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002615 }
2616 }
2617
Fabien Sanglard830b8472016-11-30 16:35:58 -08002618 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002620 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002621 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002622
2623 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002624 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625}
2626
Dan Stoza9e56aa02015-11-02 13:00:03 -08002627bool SurfaceFlinger::doComposeSurfaces(
2628 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002629{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002630 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002631
Dan Stoza9e56aa02015-11-02 13:00:03 -08002632 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002633
2634 mat4 oldColorMatrix;
2635 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2636 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2637 if (applyColorMatrix) {
2638 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2639 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2640 }
2641
Dan Stoza9e56aa02015-11-02 13:00:03 -08002642 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2643 if (hasClientComposition) {
2644 ALOGV("hasClientComposition");
2645
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002646#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002647 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002648 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002649#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002650 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002651 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002652 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002653 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002654
2655 // |mStateLock| not needed as we are on the main thread
2656 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002657 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2658 }
2659 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002660 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002661
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002662 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2664 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002665 // when using overlays, we assume a fully transparent framebuffer
2666 // NOTE: we could reduce how much we need to clear, for instance
2667 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002668 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002669 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002670 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002671 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002672 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002673 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002674
2675 // we remove the scissor part
2676 // we're left with the letterbox region
2677 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002678 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002679
2680 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002681 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002682
2683 // but limit it to the dirty region
2684 region.andSelf(dirty);
2685
Mathias Agopianb9494d52012-04-18 02:28:45 -07002686 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002687 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002688 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002689 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002690 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002691 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002692
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002694 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002695 // scissor on the main display. It should never be needed
2696 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002697 const Rect& bounds(displayDevice->getBounds());
2698 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002699 if (scissor != bounds) {
2700 // scissor doesn't match the screen's dimensions, so we
2701 // need to clear everything outside of it and enable
2702 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002703
Mathias Agopianf45c5102012-10-24 16:29:17 -07002704 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002705 const uint32_t height = displayDevice->getHeight();
2706 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002707 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002708 }
2709 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002710 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002711
Mathias Agopian85d751c2012-08-29 16:59:24 -07002712 /*
2713 * and then, render the layers targeted at the framebuffer
2714 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002715
Dan Stoza9e56aa02015-11-02 13:00:03 -08002716 ALOGV("Rendering client layers");
2717 const Transform& displayTransform = displayDevice->getTransform();
2718 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002719 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002720 bool firstLayer = true;
2721 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2722 const Region clip(dirty.intersect(
2723 displayTransform.transform(layer->visibleRegion)));
2724 ALOGV("Layer: %s", layer->getName().string());
2725 ALOGV(" Composition type: %s",
2726 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002727 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002728 switch (layer->getCompositionType(hwcId)) {
2729 case HWC2::Composition::Cursor:
2730 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002731 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002732 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002733 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002734 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002735 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002736 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002737 // never clear the very first layer since we're
2738 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002739 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002740 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002741 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002742 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002743 case HWC2::Composition::Client: {
2744 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002745 break;
2746 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002747 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002748 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002749 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002750 } else {
2751 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002752 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002753 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002754 }
2755 } else {
2756 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002757 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002758 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002759 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002760 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002761 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002762 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002763 }
2764 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002765
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002766 if (applyColorMatrix) {
2767 getRenderEngine().setupColorTransform(oldColorMatrix);
2768 }
2769
Mathias Agopianf45c5102012-10-24 16:29:17 -07002770 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002772 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773}
2774
Fabien Sanglard830b8472016-11-30 16:35:58 -08002775void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2776 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002777 RenderEngine& engine(getRenderEngine());
2778 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779}
2780
Dan Stoza7d89d062015-04-30 13:29:25 -07002781status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002782 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002783 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002784 const sp<Layer>& lbc,
2785 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002786{
Dan Stoza7d89d062015-04-30 13:29:25 -07002787 // add this layer to the current state list
2788 {
2789 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002790 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002791 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2792 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002793 return NO_MEMORY;
2794 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002795 if (parent == nullptr) {
2796 mCurrentState.layersSortedByZ.add(lbc);
2797 } else {
chaviwc9674332017-08-28 12:32:18 -07002798 bool found = false;
2799 mCurrentState.traverseInZOrder([&](Layer* layer) {
2800 if (layer == parent.get()) {
2801 found = true;
2802 }
2803 });
2804
2805 if (!found) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002806 ALOGE("addClientLayer called with a removed parent");
2807 return NAME_NOT_FOUND;
2808 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002809 parent->addChild(lbc);
2810 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002811
Dan Stoza7d89d062015-04-30 13:29:25 -07002812 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002813 mLayersAdded = true;
2814 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002815 }
2816
Mathias Agopian96f08192010-06-02 23:28:45 -07002817 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002818 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002819
Dan Stoza7d89d062015-04-30 13:29:25 -07002820 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002821}
2822
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002823status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002824 Mutex::Autolock _l(mStateLock);
2825
Robert Carr1f0a16a2016-10-24 16:27:39 -07002826 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002827 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002828 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002829 if (topLevelOnly) {
2830 return NO_ERROR;
2831 }
2832
Chia-I Wu98f1c102017-05-30 14:54:08 -07002833 sp<Layer> ancestor = p;
2834 while (ancestor->getParent() != nullptr) {
2835 ancestor = ancestor->getParent();
2836 }
2837 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2838 ALOGE("removeLayer called with a layer whose parent has been removed");
2839 return NAME_NOT_FOUND;
2840 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002841
2842 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002843 } else {
2844 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002845 }
2846
Robert Carr136e2f62017-02-08 17:54:29 -08002847 // As a matter of normal operation, the LayerCleaner will produce a second
2848 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2849 // so we will succeed in promoting it, but it's already been removed
2850 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2851 // otherwise something has gone wrong and we are leaking the layer.
2852 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002853 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2854 layer->getName().string(),
2855 (p != nullptr) ? p->getName().string() : "no-parent");
2856 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002857 } else if (index < 0) {
2858 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002859 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002860
Chia-I Wuc6657022017-08-15 11:18:17 -07002861 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002862 mLayersPendingRemoval.add(layer);
2863 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002864 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002865 setTransactionFlags(eTransactionNeeded);
2866 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867}
2868
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002869uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002870 return android_atomic_release_load(&mTransactionFlags);
2871}
2872
Mathias Agopian3f844832013-08-07 21:24:32 -07002873uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2875}
2876
Mathias Agopian3f844832013-08-07 21:24:32 -07002877uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2879 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002880 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881 }
2882 return old;
2883}
2884
Mathias Agopian8b33f032012-07-24 20:43:54 -07002885void SurfaceFlinger::setTransactionState(
2886 const Vector<ComposerState>& state,
2887 const Vector<DisplayState>& displays,
2888 uint32_t flags)
2889{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002890 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002891 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002892 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002893
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002894 if (flags & eAnimation) {
2895 // For window updates that are part of an animation we must wait for
2896 // previous animation "frames" to be handled.
2897 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002898 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002899 if (CC_UNLIKELY(err != NO_ERROR)) {
2900 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002901 // caller after a few seconds.
2902 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2903 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002904 mAnimTransactionPending = false;
2905 break;
2906 }
2907 }
2908 }
2909
Mathias Agopiane57f2922012-08-09 16:29:12 -07002910 size_t count = displays.size();
2911 for (size_t i=0 ; i<count ; i++) {
2912 const DisplayState& s(displays[i]);
2913 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002914 }
2915
Mathias Agopiane57f2922012-08-09 16:29:12 -07002916 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002917 for (size_t i=0 ; i<count ; i++) {
2918 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002919 // Here we need to check that the interface we're given is indeed
2920 // one of our own. A malicious client could give us a NULL
2921 // IInterface, or one of its own or even one of our own but a
2922 // different type. All these situations would cause us to crash.
2923 //
2924 // NOTE: it would be better to use RTTI as we could directly check
2925 // that we have a Client*. however, RTTI is disabled in Android.
2926 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002927 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002928 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002929 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002930 sp<Client> client( static_cast<Client *>(s.client.get()) );
2931 transactionFlags |= setClientStateLocked(client, s.state);
2932 }
2933 }
2934 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002935 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002936
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002937 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2938 // anyway. This can be used as a flush mechanism for previous async transactions.
2939 // Empty animation transaction can be used to simulate back-pressure, so also force a
2940 // transaction for empty animation transactions.
2941 if (transactionFlags == 0 &&
2942 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002943 transactionFlags = eTransactionNeeded;
2944 }
2945
Mathias Agopian386aa982011-11-07 21:58:03 -08002946 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002947 if (mInterceptor.isEnabled()) {
2948 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2949 }
Irvel468051e2016-06-13 16:44:44 -07002950
Mathias Agopian386aa982011-11-07 21:58:03 -08002951 // this triggers the transaction
2952 setTransactionFlags(transactionFlags);
2953
2954 // if this is a synchronous transaction, wait for it to take effect
2955 // before returning.
2956 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002957 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002958 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002959 if (flags & eAnimation) {
2960 mAnimTransactionPending = true;
2961 }
2962 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002963 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2964 if (CC_UNLIKELY(err != NO_ERROR)) {
2965 // just in case something goes wrong in SF, return to the
2966 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002967 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2968 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002969 break;
2970 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002971 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002972 }
2973}
2974
Mathias Agopiane57f2922012-08-09 16:29:12 -07002975uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2976{
Jesse Hall9a143922012-10-04 16:29:19 -07002977 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2978 if (dpyIdx < 0)
2979 return 0;
2980
Mathias Agopiane57f2922012-08-09 16:29:12 -07002981 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002982 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002983 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002984 const uint32_t what = s.what;
2985 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002986 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002987 disp.surface = s.surface;
2988 flags |= eDisplayTransactionNeeded;
2989 }
2990 }
2991 if (what & DisplayState::eLayerStackChanged) {
2992 if (disp.layerStack != s.layerStack) {
2993 disp.layerStack = s.layerStack;
2994 flags |= eDisplayTransactionNeeded;
2995 }
2996 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002997 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002998 if (disp.orientation != s.orientation) {
2999 disp.orientation = s.orientation;
3000 flags |= eDisplayTransactionNeeded;
3001 }
3002 if (disp.frame != s.frame) {
3003 disp.frame = s.frame;
3004 flags |= eDisplayTransactionNeeded;
3005 }
3006 if (disp.viewport != s.viewport) {
3007 disp.viewport = s.viewport;
3008 flags |= eDisplayTransactionNeeded;
3009 }
3010 }
Michael Lentine47e45402014-07-18 15:34:25 -07003011 if (what & DisplayState::eDisplaySizeChanged) {
3012 if (disp.width != s.width) {
3013 disp.width = s.width;
3014 flags |= eDisplayTransactionNeeded;
3015 }
3016 if (disp.height != s.height) {
3017 disp.height = s.height;
3018 flags |= eDisplayTransactionNeeded;
3019 }
3020 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003021 }
3022 return flags;
3023}
3024
3025uint32_t SurfaceFlinger::setClientStateLocked(
3026 const sp<Client>& client,
3027 const layer_state_t& s)
3028{
3029 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003030 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003031 if (layer != 0) {
3032 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003033 bool geometryAppliesWithResize =
3034 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003035 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003036 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003037 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003038 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003039 }
3040 if (what & layer_state_t::eLayerChanged) {
3041 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003042 const auto& p = layer->getParent();
3043 if (p == nullptr) {
3044 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3045 if (layer->setLayer(s.z) && idx >= 0) {
3046 mCurrentState.layersSortedByZ.removeAt(idx);
3047 mCurrentState.layersSortedByZ.add(layer);
3048 // we need traversal (state changed)
3049 // AND transaction (list changed)
3050 flags |= eTransactionNeeded|eTraversalNeeded;
3051 }
3052 } else {
3053 if (p->setChildLayer(layer, s.z)) {
3054 flags |= eTransactionNeeded|eTraversalNeeded;
3055 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003056 }
3057 }
Robert Carrdb66e622017-04-10 16:55:57 -07003058 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003059 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003060 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003061 mCurrentState.layersSortedByZ.removeAt(idx);
3062 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003063 flags |= eTransactionNeeded|eTraversalNeeded;
3064 }
3065 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003066 if (what & layer_state_t::eSizeChanged) {
3067 if (layer->setSize(s.w, s.h)) {
3068 flags |= eTraversalNeeded;
3069 }
3070 }
3071 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003072 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003073 flags |= eTraversalNeeded;
3074 }
chaviw13fdc492017-06-27 12:40:18 -07003075 if (what & layer_state_t::eColorChanged) {
3076 if (layer->setColor(s.color))
3077 flags |= eTraversalNeeded;
3078 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003079 if (what & layer_state_t::eMatrixChanged) {
3080 if (layer->setMatrix(s.matrix))
3081 flags |= eTraversalNeeded;
3082 }
3083 if (what & layer_state_t::eTransparentRegionChanged) {
3084 if (layer->setTransparentRegionHint(s.transparentRegion))
3085 flags |= eTraversalNeeded;
3086 }
Dan Stoza23116082015-06-18 14:58:39 -07003087 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003088 if (layer->setFlags(s.flags, s.mask))
3089 flags |= eTraversalNeeded;
3090 }
3091 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003092 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003093 flags |= eTraversalNeeded;
3094 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003095 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003096 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003097 flags |= eTraversalNeeded;
3098 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003099 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003100 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003101 // We only allow setting layer stacks for top level layers,
3102 // everything else inherits layer stack from its parent.
3103 if (layer->hasParent()) {
3104 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3105 layer->getName().string());
3106 } else if (idx < 0) {
3107 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3108 "that also does not appear in the top level layer list. Something"
3109 " has gone wrong.", layer->getName().string());
3110 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003111 mCurrentState.layersSortedByZ.removeAt(idx);
3112 mCurrentState.layersSortedByZ.add(layer);
3113 // we need traversal (state changed)
3114 // AND transaction (list changed)
3115 flags |= eTransactionNeeded|eTraversalNeeded;
3116 }
3117 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003118 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003119 if (s.barrierHandle != nullptr) {
3120 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3121 } else if (s.barrierGbp != nullptr) {
3122 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3123 if (authenticateSurfaceTextureLocked(gbp)) {
3124 const auto& otherLayer =
3125 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3126 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3127 } else {
3128 ALOGE("Attempt to defer transaction to to an"
3129 " unrecognized GraphicBufferProducer");
3130 }
3131 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003132 // We don't trigger a traversal here because if no other state is
3133 // changed, we don't want this to cause any more work
3134 }
chaviwf1961f72017-09-18 16:41:07 -07003135 if (what & layer_state_t::eReparent) {
3136 if (layer->reparent(s.parentHandleForChild)) {
chaviw06178942017-07-27 10:25:59 -07003137 flags |= eTransactionNeeded|eTraversalNeeded;
3138 }
3139 }
Robert Carr1db73f62016-12-21 12:58:51 -08003140 if (what & layer_state_t::eReparentChildren) {
3141 if (layer->reparentChildren(s.reparentHandle)) {
3142 flags |= eTransactionNeeded|eTraversalNeeded;
3143 }
3144 }
Robert Carr9524cb32017-02-13 11:32:32 -08003145 if (what & layer_state_t::eDetachChildren) {
3146 layer->detachChildren();
3147 }
Robert Carrc3574f72016-03-24 12:19:32 -07003148 if (what & layer_state_t::eOverrideScalingModeChanged) {
3149 layer->setOverrideScalingMode(s.overrideScalingMode);
3150 // We don't trigger a traversal here because if no other state is
3151 // changed, we don't want this to cause any more work
3152 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003153 }
3154 return flags;
3155}
3156
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003157status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003158 const String8& name,
3159 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003160 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003161 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3162 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003164 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003165 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003166 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003167 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003168 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003169
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003170 status_t result = NO_ERROR;
3171
3172 sp<Layer> layer;
3173
Cody Northropbc755282017-03-31 12:00:08 -06003174 String8 uniqueName = getUniqueLayerName(name);
3175
Mathias Agopian3165cc22012-08-08 19:42:09 -07003176 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3177 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003178 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003179 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003180 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003181 break;
chaviw13fdc492017-06-27 12:40:18 -07003182 case ISurfaceComposerClient::eFXSurfaceColor:
3183 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003184 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003185 handle, gbp, &layer);
3186 break;
3187 default:
3188 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003189 break;
3190 }
3191
Dan Stoza7d89d062015-04-30 13:29:25 -07003192 if (result != NO_ERROR) {
3193 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003194 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003195
Chia-I Wuab0c3192017-08-01 11:29:00 -07003196 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3197 // TODO b/64227542
3198 if (windowType == 441731) {
3199 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3200 layer->setPrimaryDisplayOnly();
3201 }
3202
Albert Chaulk479c60c2017-01-27 14:21:34 -05003203 layer->setInfo(windowType, ownerUid);
3204
Robert Carr1f0a16a2016-10-24 16:27:39 -07003205 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003206 if (result != NO_ERROR) {
3207 return result;
3208 }
Irvelffc9efc2016-07-27 15:16:37 -07003209 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003210
3211 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003212 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003213}
3214
Cody Northropbc755282017-03-31 12:00:08 -06003215String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3216{
3217 bool matchFound = true;
3218 uint32_t dupeCounter = 0;
3219
3220 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3221 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3222
3223 // Loop over layers until we're sure there is no matching name
3224 while (matchFound) {
3225 matchFound = false;
3226 mDrawingState.traverseInZOrder([&](Layer* layer) {
3227 if (layer->getName() == uniqueName) {
3228 matchFound = true;
3229 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3230 }
3231 });
3232 }
3233
3234 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3235
3236 return uniqueName;
3237}
3238
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003239status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3240 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3241 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242{
3243 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003244 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003245 case PIXEL_FORMAT_TRANSPARENT:
3246 case PIXEL_FORMAT_TRANSLUCENT:
3247 format = PIXEL_FORMAT_RGBA_8888;
3248 break;
3249 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003250 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003251 break;
3252 }
3253
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003254 *outLayer = new Layer(this, client, name, w, h, flags);
3255 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3256 if (err == NO_ERROR) {
3257 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003258 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003259 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003260
3261 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3262 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263}
3264
chaviw13fdc492017-06-27 12:40:18 -07003265status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003266 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3267 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268{
chaviw13fdc492017-06-27 12:40:18 -07003269 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003270 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003271 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003272 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003273}
3274
Mathias Agopianac9fa422013-02-11 16:40:36 -08003275status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003276{
Robert Carr9524cb32017-02-13 11:32:32 -08003277 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003278 status_t err = NO_ERROR;
3279 sp<Layer> l(client->getLayerUser(handle));
3280 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003281 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003282 err = removeLayer(l);
3283 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3284 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003285 }
3286 return err;
3287}
3288
Mathias Agopian13127d82013-03-05 17:47:11 -08003289status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003290{
Mathias Agopian67106042013-03-14 19:18:13 -07003291 // called by ~LayerCleaner() when all references to the IBinder (handle)
3292 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003293 sp<Layer> l = layer.promote();
3294 if (l == nullptr) {
3295 // The layer has already been removed, carry on
3296 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003297 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003298 // If we have a parent, then we can continue to live as long as it does.
3299 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003300}
3301
Mathias Agopianb60314a2012-04-10 22:09:54 -07003302// ---------------------------------------------------------------------------
3303
Andy McFadden13a082e2012-08-24 10:16:42 -07003304void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003305 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003306 Vector<ComposerState> state;
3307 Vector<DisplayState> displays;
3308 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003309 d.what = DisplayState::eDisplayProjectionChanged |
3310 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003311 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003312 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003313 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003314 d.frame.makeInvalid();
3315 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003316 d.width = 0;
3317 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003318 displays.add(d);
3319 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003320 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3321 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003322
Dan Stoza9e56aa02015-11-02 13:00:03 -08003323 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3324 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003325 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003326
Brian Andersond0010582017-03-07 13:20:31 -08003327 // Use phase of 0 since phase is not known.
3328 // Use latency of 0, which will snap to the ideal latency.
3329 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003330}
3331
3332void SurfaceFlinger::initializeDisplays() {
3333 class MessageScreenInitialized : public MessageBase {
3334 SurfaceFlinger* flinger;
3335 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003336 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003337 virtual bool handler() {
3338 flinger->onInitializeDisplays();
3339 return true;
3340 }
3341 };
3342 sp<MessageBase> msg = new MessageScreenInitialized(this);
3343 postMessageAsync(msg); // we may be called from main thread, use async message
3344}
3345
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003346void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003347 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003348 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3349 this);
3350 int32_t type = hw->getDisplayType();
3351 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003352
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003353 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003354 return;
3355 }
3356
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003357 hw->setPowerMode(mode);
3358 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3359 ALOGW("Trying to set power mode for virtual display");
3360 return;
3361 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003362
Irvelffc9efc2016-07-27 15:16:37 -07003363 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003364 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003365 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3366 if (idx < 0) {
3367 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3368 return;
3369 }
3370 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3371 }
3372
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003373 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003374 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003375 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003376 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3377 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003378 // FIXME: eventthread only knows about the main display right now
3379 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003380 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003381 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003382
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003383 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003384 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003385 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003386
3387 struct sched_param param = {0};
3388 param.sched_priority = 1;
3389 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3390 ALOGW("Couldn't set SCHED_FIFO on display on");
3391 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003392 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003393 // Turn off the display
3394 struct sched_param param = {0};
3395 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3396 ALOGW("Couldn't set SCHED_OTHER on display off");
3397 }
3398
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003399 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003400 disableHardwareVsync(true); // also cancels any in-progress resync
3401
Mathias Agopiancde87a32012-09-13 14:09:01 -07003402 // FIXME: eventthread only knows about the main display right now
3403 mEventThread->onScreenReleased();
3404 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003405
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003406 getHwComposer().setPowerMode(type, mode);
3407 mVisibleRegionsDirty = true;
3408 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003409 } else if (mode == HWC_POWER_MODE_DOZE ||
3410 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003411 // Update display while dozing
3412 getHwComposer().setPowerMode(type, mode);
3413 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3414 // FIXME: eventthread only knows about the main display right now
3415 mEventThread->onScreenAcquired();
3416 resyncToHardwareVsync(true);
3417 }
3418 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3419 // Leave display going to doze
3420 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3421 disableHardwareVsync(true); // also cancels any in-progress resync
3422 // FIXME: eventthread only knows about the main display right now
3423 mEventThread->onScreenReleased();
3424 }
3425 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003426 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003427 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003428 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003429 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003430}
3431
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003432void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3433 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003434 SurfaceFlinger& mFlinger;
3435 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003436 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003437 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003438 MessageSetPowerMode(SurfaceFlinger& flinger,
3439 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3440 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003441 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003442 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003443 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003444 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003445 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003446 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003447 ALOGW("Attempt to set power mode = %d for virtual display",
3448 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003449 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003450 mFlinger.setPowerModeInternal(
3451 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003452 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003453 return true;
3454 }
3455 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003456 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003457 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003458}
3459
3460// ---------------------------------------------------------------------------
3461
Vishnu Nair35798872017-10-06 16:00:36 -07003462status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003463 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003464
Mathias Agopianbd115332013-04-18 16:41:04 -07003465 IPCThreadState* ipc = IPCThreadState::self();
3466 const int pid = ipc->getCallingPid();
3467 const int uid = ipc->getCallingUid();
3468 if ((uid != AID_SHELL) &&
3469 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003470 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003471 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003472 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003473 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003474 // (this would indicate SF is stuck, but we want to be able to
3475 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003476 status_t err = mStateLock.timedLock(s2ns(1));
3477 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003478 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003479 result.appendFormat(
3480 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3481 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003482 }
3483
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003484 bool dumpAll = true;
3485 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003486 size_t numArgs = args.size();
3487 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003488 if ((index < numArgs) &&
3489 (args[index] == String16("--list"))) {
3490 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003491 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003492 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003493 }
3494
3495 if ((index < numArgs) &&
3496 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003497 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003498 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003499 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003500 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003501
3502 if ((index < numArgs) &&
3503 (args[index] == String16("--latency-clear"))) {
3504 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003505 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003506 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003507 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003508
3509 if ((index < numArgs) &&
3510 (args[index] == String16("--dispsync"))) {
3511 index++;
3512 mPrimaryDispSync.dump(result);
3513 dumpAll = false;
3514 }
Dan Stozab90cf072015-03-05 11:05:59 -08003515
3516 if ((index < numArgs) &&
3517 (args[index] == String16("--static-screen"))) {
3518 index++;
3519 dumpStaticScreenStats(result);
3520 dumpAll = false;
3521 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003522
3523 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003524 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003525 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003526 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003527 dumpAll = false;
3528 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003529
3530 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3531 index++;
3532 dumpWideColorInfo(result);
3533 dumpAll = false;
3534 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003535 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003536
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003537 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003538 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003539 }
3540
Mathias Agopian9795c422009-08-26 16:36:26 -07003541 if (locked) {
3542 mStateLock.unlock();
3543 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003544 }
3545 write(fd, result.string(), result.size());
3546 return NO_ERROR;
3547}
3548
Dan Stozac7014012014-02-14 15:03:43 -08003549void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3550 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003551{
Robert Carr2047fae2016-11-28 14:09:09 -08003552 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003553 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003554 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003555}
3556
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003557void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003558 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003559{
3560 String8 name;
3561 if (index < args.size()) {
3562 name = String8(args[index]);
3563 index++;
3564 }
3565
Dan Stoza9e56aa02015-11-02 13:00:03 -08003566 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3567 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003568 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003569
3570 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003571 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003572 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003573 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003574 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003575 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003576 }
Robert Carr2047fae2016-11-28 14:09:09 -08003577 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003578 }
3579}
3580
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003581void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003582 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003583{
3584 String8 name;
3585 if (index < args.size()) {
3586 name = String8(args[index]);
3587 index++;
3588 }
3589
Robert Carr2047fae2016-11-28 14:09:09 -08003590 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003591 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003592 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003593 }
Robert Carr2047fae2016-11-28 14:09:09 -08003594 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003595
Svetoslavd85084b2014-03-20 10:28:31 -07003596 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003597}
3598
Jamie Gennis6547ff42013-07-16 20:12:42 -07003599// This should only be called from the main thread. Otherwise it would need
3600// the lock and should use mCurrentState rather than mDrawingState.
3601void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003602 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003603 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003604 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003605
3606 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3607}
3608
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003609void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003610{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003611 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003612 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3613
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003614 if (isLayerTripleBufferingDisabled())
3615 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003616
3617 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003618 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003619 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003620 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003621 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3622 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003623 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003624}
3625
Dan Stozab90cf072015-03-05 11:05:59 -08003626void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3627{
3628 result.appendFormat("Static screen stats:\n");
3629 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3630 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3631 float percent = 100.0f *
3632 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3633 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3634 b + 1, bucketTimeSec, percent);
3635 }
3636 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3637 float percent = 100.0f *
3638 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3639 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3640 NUM_BUCKETS - 1, bucketTimeSec, percent);
3641}
3642
Dan Stozae77c7662016-05-13 11:37:28 -07003643void SurfaceFlinger::recordBufferingStats(const char* layerName,
3644 std::vector<OccupancyTracker::Segment>&& history) {
3645 Mutex::Autolock lock(mBufferingStatsMutex);
3646 auto& stats = mBufferingStats[layerName];
3647 for (const auto& segment : history) {
3648 if (!segment.usedThirdBuffer) {
3649 stats.twoBufferTime += segment.totalTime;
3650 }
3651 if (segment.occupancyAverage < 1.0f) {
3652 stats.doubleBufferedTime += segment.totalTime;
3653 } else if (segment.occupancyAverage < 2.0f) {
3654 stats.tripleBufferedTime += segment.totalTime;
3655 }
3656 ++stats.numSegments;
3657 stats.totalTime += segment.totalTime;
3658 }
3659}
3660
Brian Andersond6927fb2016-07-23 23:37:30 -07003661void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3662 result.appendFormat("Layer frame timestamps:\n");
3663
3664 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3665 const size_t count = currentLayers.size();
3666 for (size_t i=0 ; i<count ; i++) {
3667 currentLayers[i]->dumpFrameEvents(result);
3668 }
3669}
3670
Dan Stozae77c7662016-05-13 11:37:28 -07003671void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3672 result.append("Buffering stats:\n");
3673 result.append(" [Layer name] <Active time> <Two buffer> "
3674 "<Double buffered> <Triple buffered>\n");
3675 Mutex::Autolock lock(mBufferingStatsMutex);
3676 typedef std::tuple<std::string, float, float, float> BufferTuple;
3677 std::map<float, BufferTuple, std::greater<float>> sorted;
3678 for (const auto& statsPair : mBufferingStats) {
3679 const char* name = statsPair.first.c_str();
3680 const BufferingStats& stats = statsPair.second;
3681 if (stats.numSegments == 0) {
3682 continue;
3683 }
3684 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3685 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3686 stats.totalTime;
3687 float doubleBufferRatio = static_cast<float>(
3688 stats.doubleBufferedTime) / stats.totalTime;
3689 float tripleBufferRatio = static_cast<float>(
3690 stats.tripleBufferedTime) / stats.totalTime;
3691 sorted.insert({activeTime, {name, twoBufferRatio,
3692 doubleBufferRatio, tripleBufferRatio}});
3693 }
3694 for (const auto& sortedPair : sorted) {
3695 float activeTime = sortedPair.first;
3696 const BufferTuple& values = sortedPair.second;
3697 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3698 std::get<0>(values).c_str(), activeTime,
3699 std::get<1>(values), std::get<2>(values),
3700 std::get<3>(values));
3701 }
3702 result.append("\n");
3703}
3704
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003705void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3706 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3707
3708 // TODO: print out if wide-color mode is active or not
3709
3710 for (size_t d = 0; d < mDisplays.size(); d++) {
3711 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3712 int32_t hwcId = displayDevice->getHwcDisplayId();
3713 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3714 continue;
3715 }
3716
3717 result.appendFormat("Display %d color modes:\n", hwcId);
3718 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3719 for (auto&& mode : modes) {
3720 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3721 }
3722
3723 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3724 result.appendFormat(" Current color mode: %s (%d)\n",
3725 decodeColorMode(currentMode).c_str(), currentMode);
3726 }
3727 result.append("\n");
3728}
3729
Mathias Agopian74d211a2013-04-22 16:55:35 +02003730void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3731 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003732{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003733 bool colorize = false;
3734 if (index < args.size()
3735 && (args[index] == String16("--color"))) {
3736 colorize = true;
3737 index++;
3738 }
3739
3740 Colorizer colorizer(colorize);
3741
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003742 // figure out if we're stuck somewhere
3743 const nsecs_t now = systemTime();
3744 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3745 const nsecs_t inTransaction(mDebugInTransaction);
3746 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3747 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3748
3749 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003750 * Dump library configuration.
3751 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003752
3753 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003754 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003755 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003756 appendSfConfigString(result);
3757 appendUiConfigString(result);
3758 appendGuiConfigString(result);
3759 result.append("\n");
3760
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003761 result.append("\nWide-Color information:\n");
3762 dumpWideColorInfo(result);
3763
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003764 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003765 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003766 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003767 result.append(SyncFeatures::getInstance().toString());
3768 result.append("\n");
3769
Dan Stoza9e56aa02015-11-02 13:00:03 -08003770 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3771
Andy McFadden41d67d72014-04-25 16:58:34 -07003772 colorizer.bold(result);
3773 result.append("DispSync configuration: ");
3774 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003775 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003776 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003777 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003778 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003779 result.append("\n");
3780
Dan Stozab90cf072015-03-05 11:05:59 -08003781 // Dump static screen stats
3782 result.append("\n");
3783 dumpStaticScreenStats(result);
3784 result.append("\n");
3785
Dan Stozae77c7662016-05-13 11:37:28 -07003786 dumpBufferingStats(result);
3787
Andy McFadden4803b742012-09-24 19:07:20 -07003788 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003789 * Dump the visible layer list
3790 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003791 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003792 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003793 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003794 mCurrentState.traverseInZOrder([&](Layer* layer) {
Kalle Raitaa099a242017-01-11 11:17:29 -08003795 result.append(to_string(layer->getLayerDebugInfo()).c_str());
Robert Carr2047fae2016-11-28 14:09:09 -08003796 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003797
3798 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003799 * Dump Display state
3800 */
3801
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003802 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003803 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003804 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003805 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3806 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003807 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003808 }
3809
3810 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003811 * Dump SurfaceFlinger global state
3812 */
3813
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003814 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003815 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003816 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003817
Mathias Agopian888c8222012-08-04 21:10:38 -07003818 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003819 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003820
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003821 colorizer.bold(result);
3822 result.appendFormat("EGL implementation : %s\n",
3823 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3824 colorizer.reset(result);
3825 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003826 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003827
Mathias Agopian875d8e12013-06-07 15:35:48 -07003828 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003829
Mathias Agopian42977342012-08-05 00:40:46 -07003830 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003831 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3832 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003833 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003834 " last eglSwapBuffers() time: %f us\n"
3835 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003836 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003837 " refresh-rate : %f fps\n"
3838 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003839 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003840 " gpu_to_cpu_unsupported : %d\n"
3841 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003842 mLastSwapBufferTime/1000.0,
3843 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003844 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003845 1e9 / activeConfig->getVsyncPeriod(),
3846 activeConfig->getDpiX(),
3847 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003848 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003849
Mathias Agopian74d211a2013-04-22 16:55:35 +02003850 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003851 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003852
Mathias Agopian74d211a2013-04-22 16:55:35 +02003853 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003854 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003855
3856 /*
3857 * VSYNC state
3858 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003859 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003860 result.append("\n");
3861
3862 /*
3863 * HWC layer minidump
3864 */
3865 for (size_t d = 0; d < mDisplays.size(); d++) {
3866 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3867 int32_t hwcId = displayDevice->getHwcDisplayId();
3868 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3869 continue;
3870 }
3871
3872 result.appendFormat("Display %d HWC layers:\n", hwcId);
3873 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003874 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003875 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003876 });
Dan Stozae22aec72016-08-01 13:20:59 -07003877 result.append("\n");
3878 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003879
3880 /*
3881 * Dump HWComposer state
3882 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003883 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003884 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003885 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003886 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003887 result.appendFormat(" h/w composer %s\n",
3888 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003889 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003890
3891 /*
3892 * Dump gralloc state
3893 */
3894 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3895 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003896
3897 /*
3898 * Dump VrFlinger state if in use.
3899 */
3900 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3901 result.append("VrFlinger state:\n");
3902 result.append(mVrFlinger->Dump().c_str());
3903 result.append("\n");
3904 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003905}
3906
Mathias Agopian13127d82013-03-05 17:47:11 -08003907const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003908SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003909 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003910 wp<IBinder> dpy;
3911 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3912 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3913 dpy = mDisplays.keyAt(i);
3914 break;
3915 }
3916 }
3917 if (dpy == NULL) {
3918 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3919 // Just use the primary display so we have something to return
3920 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3921 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003922 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003923}
3924
Keun young Park63f165f2012-08-31 10:53:36 -07003925bool SurfaceFlinger::startDdmConnection()
3926{
3927 void* libddmconnection_dso =
3928 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3929 if (!libddmconnection_dso) {
3930 return false;
3931 }
3932 void (*DdmConnection_start)(const char* name);
3933 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003934 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003935 if (!DdmConnection_start) {
3936 dlclose(libddmconnection_dso);
3937 return false;
3938 }
3939 (*DdmConnection_start)(getServiceName());
3940 return true;
3941}
3942
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003943status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003944 switch (code) {
3945 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003946 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003947 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003948 case CLEAR_ANIMATION_FRAME_STATS:
3949 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003950 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003951 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003952 {
3953 // codes that require permission check
3954 IPCThreadState* ipc = IPCThreadState::self();
3955 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003956 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003957 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003958 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003959 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003960 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003961 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003962 break;
3963 }
Robert Carr1db73f62016-12-21 12:58:51 -08003964 /*
3965 * Calling setTransactionState is safe, because you need to have been
3966 * granted a reference to Client* and Handle* to do anything with it.
3967 *
3968 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3969 */
3970 case SET_TRANSACTION_STATE:
3971 case CREATE_SCOPED_CONNECTION:
3972 {
3973 return OK;
3974 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003975 case CAPTURE_SCREEN:
3976 {
3977 // codes that require permission check
3978 IPCThreadState* ipc = IPCThreadState::self();
3979 const int pid = ipc->getCallingPid();
3980 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003981 if ((uid != AID_GRAPHICS) &&
3982 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003983 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003984 return PERMISSION_DENIED;
3985 }
3986 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003987 }
3988 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003989 return OK;
3990}
3991
3992status_t SurfaceFlinger::onTransact(
3993 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3994{
3995 status_t credentialCheck = CheckTransactCodeCredentials(code);
3996 if (credentialCheck != OK) {
3997 return credentialCheck;
3998 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003999
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004000 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4001 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004002 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004003 IPCThreadState* ipc = IPCThreadState::self();
4004 const int uid = ipc->getCallingUid();
4005 if (CC_UNLIKELY(uid != AID_SYSTEM
4006 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004007 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004008 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004009 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004010 return PERMISSION_DENIED;
4011 }
4012 int n;
4013 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004014 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004015 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004016 return NO_ERROR;
4017 case 1002: // SHOW_UPDATES
4018 n = data.readInt32();
4019 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004020 invalidateHwcGeometry();
4021 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004022 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004023 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004024 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004025 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004026 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004027 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004028 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004029 setTransactionFlags(
4030 eTransactionNeeded|
4031 eDisplayTransactionNeeded|
4032 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004033 return NO_ERROR;
4034 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004035 case 1006:{ // send empty update
4036 signalRefresh();
4037 return NO_ERROR;
4038 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004039 case 1008: // toggle use of hw composer
4040 n = data.readInt32();
4041 mDebugDisableHWC = n ? 1 : 0;
4042 invalidateHwcGeometry();
4043 repaintEverything();
4044 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004045 case 1009: // toggle use of transform hint
4046 n = data.readInt32();
4047 mDebugDisableTransformHint = n ? 1 : 0;
4048 invalidateHwcGeometry();
4049 repaintEverything();
4050 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004051 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004052 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004053 reply->writeInt32(0);
4054 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004055 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004056 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004057 return NO_ERROR;
4058 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004059 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004060 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004061 return NO_ERROR;
4062 }
4063 case 1014: {
4064 // daltonize
4065 n = data.readInt32();
4066 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004067 case 1:
4068 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4069 break;
4070 case 2:
4071 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4072 break;
4073 case 3:
4074 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4075 break;
4076 default:
4077 mDaltonizer.setType(ColorBlindnessType::None);
4078 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004079 }
4080 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004081 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004082 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004083 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004084 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004085 invalidateHwcGeometry();
4086 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004087 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004088 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004089 case 1015: {
4090 // apply a color matrix
4091 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004092 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004093 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004094 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004095 for (size_t j = 0; j < 4; j++) {
4096 mColorMatrix[i][j] = data.readFloat();
4097 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004098 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004099 } else {
4100 mColorMatrix = mat4();
4101 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004102
4103 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4104 // the division by w in the fragment shader
4105 float4 lastRow(transpose(mColorMatrix)[3]);
4106 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4107 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4108 }
4109
Alan Viverette9c5a3332013-09-12 20:04:35 -07004110 invalidateHwcGeometry();
4111 repaintEverything();
4112 return NO_ERROR;
4113 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004114 // This is an experimental interface
4115 // Needs to be shifted to proper binder interface when we productize
4116 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004117 n = data.readInt32();
4118 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004119 return NO_ERROR;
4120 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004121 case 1017: {
4122 n = data.readInt32();
4123 mForceFullDamage = static_cast<bool>(n);
4124 return NO_ERROR;
4125 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004126 case 1018: { // Modify Choreographer's phase offset
4127 n = data.readInt32();
4128 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4129 return NO_ERROR;
4130 }
4131 case 1019: { // Modify SurfaceFlinger's phase offset
4132 n = data.readInt32();
4133 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4134 return NO_ERROR;
4135 }
Irvel468051e2016-06-13 16:44:44 -07004136 case 1020: { // Layer updates interceptor
4137 n = data.readInt32();
4138 if (n) {
4139 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004140 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004141 }
4142 else{
4143 ALOGV("Interceptor disabled");
4144 mInterceptor.disable();
4145 }
4146 return NO_ERROR;
4147 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004148 case 1021: { // Disable HWC virtual displays
4149 n = data.readInt32();
4150 mUseHwcVirtualDisplays = !n;
4151 return NO_ERROR;
4152 }
Romain Guy0147a172017-06-01 13:53:56 -07004153 case 1022: { // Set saturation boost
4154 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4155
4156 invalidateHwcGeometry();
4157 repaintEverything();
4158 return NO_ERROR;
4159 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004160 }
4161 }
4162 return err;
4163}
4164
Steven Thomas6d8110b2017-08-31 18:24:21 -07004165void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004166 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004167 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004168}
4169
Steven Thomas6d8110b2017-08-31 18:24:21 -07004170void SurfaceFlinger::repaintEverything() {
4171 ConditionalLock _l(mStateLock,
4172 std::this_thread::get_id() != mMainThreadId);
4173 repaintEverythingLocked();
4174}
4175
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004176// Checks that the requested width and height are valid and updates them to the display dimensions
4177// if they are set to 0
4178static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4179 Transform::orientation_flags rotation,
4180 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4181 // get screen geometry
4182 uint32_t displayWidth = displayDevice->getWidth();
4183 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004184
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004185 if (rotation & Transform::ROT_90) {
4186 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004187 }
4188
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004189 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4190 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4191 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4192 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004193 }
4194
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004195 if (*requestedWidth == 0) {
4196 *requestedWidth = displayWidth;
4197 }
4198 if (*requestedHeight == 0) {
4199 *requestedHeight = displayHeight;
4200 }
4201
4202 return NO_ERROR;
4203}
4204
4205// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4206class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004207public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004208 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4209 ~WindowDisconnector() {
4210 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004211 }
4212
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004213private:
4214 ANativeWindow* mWindow;
4215 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004216};
4217
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004218static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4219 uint32_t requestedHeight, bool hasWideColorDisplay,
4220 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4221 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4222 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4223
4224 int err = 0;
4225 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4226 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4227 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4228 err |= native_window_set_usage(window, usage);
4229
4230 if (hasWideColorDisplay) {
4231 err |= native_window_set_buffers_data_space(window,
4232 renderEngineUsesWideColor
4233 ? HAL_DATASPACE_DISPLAY_P3
4234 : HAL_DATASPACE_V0_SRGB);
4235 }
4236
4237 if (err != NO_ERROR) {
4238 return BAD_VALUE;
4239 }
4240
4241 /* TODO: Once we have the sync framework everywhere this can use
4242 * server-side waits on the fence that dequeueBuffer returns.
4243 */
4244 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4245 if (err != NO_ERROR) {
4246 return err;
4247 }
4248
4249 return NO_ERROR;
4250}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004251
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004252status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4253 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004254 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004255 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004256 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004257 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004258
4259 if (CC_UNLIKELY(display == 0))
4260 return BAD_VALUE;
4261
4262 if (CC_UNLIKELY(producer == 0))
4263 return BAD_VALUE;
4264
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004265 // if we have secure windows on this display, never allow the screen capture
4266 // unless the producer interface is local (i.e.: we can take a screenshot for
4267 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004268 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004269
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004270 // Convert to surfaceflinger's internal rotation type.
4271 Transform::orientation_flags rotationFlags;
4272 switch (rotation) {
4273 case ISurfaceComposer::eRotateNone:
4274 rotationFlags = Transform::ROT_0;
4275 break;
4276 case ISurfaceComposer::eRotate90:
4277 rotationFlags = Transform::ROT_90;
4278 break;
4279 case ISurfaceComposer::eRotate180:
4280 rotationFlags = Transform::ROT_180;
4281 break;
4282 case ISurfaceComposer::eRotate270:
4283 rotationFlags = Transform::ROT_270;
4284 break;
4285 default:
4286 rotationFlags = Transform::ROT_0;
4287 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4288 break;
4289 }
4290
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004291 { // Autolock scope
4292 Mutex::Autolock lock(mStateLock);
4293 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4294 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004295 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004296
4297 // create a surface (because we're a producer, and we need to
4298 // dequeue/queue a buffer)
4299 sp<Surface> surface = new Surface(producer, false);
4300
4301 // Put the screenshot Surface into async mode so that
4302 // Layer::headFenceHasSignaled will always return true and we'll latch the
4303 // first buffer regardless of whether or not its acquire fence has
4304 // signaled. This is needed to avoid a race condition in the rotation
4305 // animation. See b/30209608
4306 surface->setAsyncMode(true);
4307
4308 ANativeWindow* window = surface.get();
4309
4310 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4311 if (result != NO_ERROR) {
4312 return result;
4313 }
4314 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4315
4316 ANativeWindowBuffer* buffer = nullptr;
4317 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4318 getRenderEngine().usesWideColor(), &buffer);
4319 if (result != NO_ERROR) {
4320 return result;
4321 }
4322
4323 // This mutex protects syncFd and captureResult for communication of the return values from the
4324 // main thread back to this Binder thread
4325 std::mutex captureMutex;
4326 std::condition_variable captureCondition;
4327 std::unique_lock<std::mutex> captureLock(captureMutex);
4328 int syncFd = -1;
4329 std::optional<status_t> captureResult;
4330
4331 sp<LambdaMessage> message = new LambdaMessage([&]() {
4332 // If there is a refresh pending, bug out early and tell the binder thread to try again
4333 // after the refresh.
4334 if (mRefreshPending) {
4335 ATRACE_NAME("Skipping screenshot for now");
4336 std::unique_lock<std::mutex> captureLock(captureMutex);
4337 captureResult = std::make_optional<status_t>(EAGAIN);
4338 captureCondition.notify_one();
4339 return;
4340 }
4341
4342 status_t result = NO_ERROR;
4343 int fd = -1;
4344 {
4345 Mutex::Autolock _l(mStateLock);
4346 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4347 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4348 minLayerZ, maxLayerZ, useIdentityTransform,
4349 rotationFlags, isLocalScreenshot, &fd);
4350 }
4351
4352 {
4353 std::unique_lock<std::mutex> captureLock(captureMutex);
4354 syncFd = fd;
4355 captureResult = std::make_optional<status_t>(result);
4356 captureCondition.notify_one();
4357 }
4358 });
4359
4360 result = postMessageAsync(message);
4361 if (result == NO_ERROR) {
4362 captureCondition.wait(captureLock, [&]() { return captureResult; });
4363 while (*captureResult == EAGAIN) {
4364 captureResult.reset();
4365 result = postMessageAsync(message);
4366 if (result != NO_ERROR) {
4367 return result;
4368 }
4369 captureCondition.wait(captureLock, [&]() { return captureResult; });
4370 }
4371 result = *captureResult;
4372 }
4373
4374 if (result == NO_ERROR) {
4375 // queueBuffer takes ownership of syncFd
4376 result = window->queueBuffer(window, buffer, syncFd);
4377 }
4378
4379 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004380}
4381
Mathias Agopian180f10d2013-04-10 22:55:41 -07004382
4383void SurfaceFlinger::renderScreenImplLocked(
4384 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004385 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004386 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004387 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004388{
4389 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004390 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004391
4392 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004393 const int32_t hw_w = hw->getWidth();
4394 const int32_t hw_h = hw->getHeight();
4395 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004396 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004397
Dan Stozac1879002014-05-22 15:59:05 -07004398 // if a default or invalid sourceCrop is passed in, set reasonable values
4399 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4400 !sourceCrop.isValid()) {
4401 sourceCrop.setLeftTop(Point(0, 0));
4402 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4403 }
4404
4405 // ensure that sourceCrop is inside screen
4406 if (sourceCrop.left < 0) {
4407 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4408 }
Dan Stozabe31f442014-06-11 11:20:54 -07004409 if (sourceCrop.right > hw_w) {
4410 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004411 }
4412 if (sourceCrop.top < 0) {
4413 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4414 }
Dan Stozabe31f442014-06-11 11:20:54 -07004415 if (sourceCrop.bottom > hw_h) {
4416 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004417 }
4418
Romain Guy88d37dd2017-05-26 17:57:05 -07004419#ifdef USE_HWC2
4420 engine.setWideColor(hw->getWideColorSupport());
4421 engine.setColorMode(hw->getActiveColorMode());
4422#endif
4423
Mathias Agopian180f10d2013-04-10 22:55:41 -07004424 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004425 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004426
4427 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004428 engine.setViewportAndProjection(
4429 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004430 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004431
4432 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004433 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004434
Robert Carr1f0a16a2016-10-24 16:27:39 -07004435 // We loop through the first level of layers without traversing,
4436 // as we need to interpret min/max layer Z in the top level Z space.
4437 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004438 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004439 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004440 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004441 const Layer::State& state(layer->getDrawingState());
4442 if (state.z < minLayerZ || state.z > maxLayerZ) {
4443 continue;
4444 }
Dan Stoza412903f2017-04-27 13:42:17 -07004445 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004446 if (!layer->isVisible()) {
4447 return;
4448 }
4449 if (filtering) layer->setFiltering(true);
4450 layer->draw(hw, useIdentityTransform);
4451 if (filtering) layer->setFiltering(false);
4452 });
4453 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004454
Mathias Agopian931bda12013-08-28 18:11:46 -07004455 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004456}
4457
Dan Stozaabcda352017-06-01 14:37:39 -07004458// A simple RAII class that holds an EGLImage and destroys it either:
4459// a) When the destroy() method is called
4460// b) When the object goes out of scope
4461class ImageHolder {
4462public:
4463 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4464 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004465
Dan Stozaabcda352017-06-01 14:37:39 -07004466 void destroy() {
4467 if (mImage != EGL_NO_IMAGE_KHR) {
4468 eglDestroyImageKHR(mDisplay, mImage);
4469 mImage = EGL_NO_IMAGE_KHR;
4470 }
4471 }
4472
4473private:
4474 const EGLDisplay mDisplay;
4475 EGLImageKHR mImage;
4476};
4477
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004478status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4479 ANativeWindowBuffer* buffer, Rect sourceCrop,
4480 uint32_t reqWidth, uint32_t reqHeight,
4481 int32_t minLayerZ, int32_t maxLayerZ,
4482 bool useIdentityTransform,
4483 Transform::orientation_flags rotation,
4484 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004485 ATRACE_CALL();
4486
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004487 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004488 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004489 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004490 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004491 (state.z < minLayerZ || state.z > maxLayerZ)) {
4492 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004493 }
Dan Stoza412903f2017-04-27 13:42:17 -07004494 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004495 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4496 layer->isSecure());
4497 });
4498 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004499
4500 if (!isLocalScreenshot && secureLayerIsVisible) {
4501 ALOGW("FB is protected: PERMISSION_DENIED");
4502 return PERMISSION_DENIED;
4503 }
4504
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004505 int syncFd = -1;
4506 // create an EGLImage from the buffer so we can later
4507 // turn it into a texture
4508 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4509 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4510 if (image == EGL_NO_IMAGE_KHR) {
4511 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004512 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004513
Dan Stozaabcda352017-06-01 14:37:39 -07004514 // This will automatically destroy the image if we return before calling its destroy method
4515 ImageHolder imageHolder(mEGLDisplay, image);
4516
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004517 // this binds the given EGLImage as a framebuffer for the
4518 // duration of this scope.
4519 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004520 if (imageBond.getStatus() != NO_ERROR) {
4521 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004522 return INVALID_OPERATION;
4523 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004524
Dan Stozaabcda352017-06-01 14:37:39 -07004525 // this will in fact render into our dequeued buffer
4526 // via an FBO, which means we didn't have to create
4527 // an EGLSurface and therefore we're not
4528 // dependent on the context's EGLConfig.
4529 renderScreenImplLocked(
4530 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4531 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004532
Dan Stozaabcda352017-06-01 14:37:39 -07004533 // Attempt to create a sync khr object that can produce a sync point. If that
4534 // isn't available, create a non-dupable sync object in the fallback path and
4535 // wait on it directly.
4536 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4537 if (!DEBUG_SCREENSHOTS) {
4538 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4539 // native fence fd will not be populated until flush() is done.
4540 getRenderEngine().flush();
4541 }
4542
4543 if (sync != EGL_NO_SYNC_KHR) {
4544 // get the sync fd
4545 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4546 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4547 ALOGW("captureScreen: failed to dup sync khr object");
4548 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004549 }
Dan Stozaabcda352017-06-01 14:37:39 -07004550 eglDestroySyncKHR(mEGLDisplay, sync);
4551 } else {
4552 // fallback path
4553 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004554 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004555 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4556 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4557 EGLint eglErr = eglGetError();
4558 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4559 ALOGW("captureScreen: fence wait timed out");
4560 } else {
4561 ALOGW_IF(eglErr != EGL_SUCCESS,
4562 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004563 }
4564 eglDestroySyncKHR(mEGLDisplay, sync);
4565 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004566 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004567 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004568 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004569 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004570
4571 if (DEBUG_SCREENSHOTS) {
4572 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4573 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4574 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4575 hw, minLayerZ, maxLayerZ);
4576 delete [] pixels;
4577 }
4578
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004579 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004580 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004581
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004582 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004583}
4584
Mathias Agopiand5556842013-09-19 17:08:37 -07004585void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004586 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004587 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004588 for (size_t y=0 ; y<h ; y++) {
4589 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4590 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004591 if (p[x] != 0xFF000000) return;
4592 }
4593 }
4594 ALOGE("*** we just took a black screenshot ***\n"
4595 "requested minz=%d, maxz=%d, layerStack=%d",
4596 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004597
Robert Carr2047fae2016-11-28 14:09:09 -08004598 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004599 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004600 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004601 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004602 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004603 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004604 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4605 layer->isVisible() ? '+' : '-',
4606 i, layer->getName().string(), layer->getLayerStack(), state.z,
chaviw13fdc492017-06-27 12:40:18 -07004607 layer->isVisible(), state.flags, static_cast<float>(state.color.a));
Robert Carr1f0a16a2016-10-24 16:27:39 -07004608 i++;
4609 });
4610 }
4611 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004612 }
4613}
4614
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004615// ---------------------------------------------------------------------------
4616
Dan Stoza412903f2017-04-27 13:42:17 -07004617void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4618 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004619}
4620
Dan Stoza412903f2017-04-27 13:42:17 -07004621void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4622 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004623}
4624
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004625}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004626
4627
4628#if defined(__gl_h_)
4629#error "don't include gl/gl.h in this file"
4630#endif
4631
4632#if defined(__gl2_h_)
4633#error "don't include gl2/gl2.h in this file"
4634#endif