blob: a51a79dea54ecf3235ae8c6f2b1eb1fbb84b1138 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
31#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080040#include <dvr/vr_flinger.h>
41
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060042#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070044#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070045
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080049#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080050#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051
52#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080055
Mathias Agopiancde87a32012-09-13 14:09:01 -070056#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/String8.h>
58#include <utils/String16.h>
59#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070060#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian921e6ac2012-07-23 23:11:29 -070063#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070064#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070070#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093#define DISPLAY_COUNT 1
94
Mathias Agopianfee2b462013-07-03 12:34:01 -070095/*
96 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
97 * black pixels.
98 */
99#define DEBUG_SCREENSHOTS false
100
Jiyong Park00b15b82017-08-10 20:30:56 +0900101extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
Mathias Agopianca088332013-03-28 17:44:13 -0700102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
Steven Thomasb02664d2017-07-26 18:48:28 -0700108namespace {
109class ConditionalLock {
110public:
111 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
112 if (lock) {
113 mMutex.lock();
114 }
115 }
116 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
117private:
118 Mutex& mMutex;
119 bool mLocked;
120};
121} // namespace anonymous
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800131int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
132int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700133bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700134int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700135bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800136uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800137bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800138bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800139int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700158 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700160 mTransactionPending(false),
161 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700162 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700163 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700164 mRepaintEverything(0),
Kalle Raitaa099a242017-01-11 11:17:29 -0800165 mHwcServiceName(getHwcServiceName()),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800166 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800168 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800170 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800171 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800172 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700173 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700174 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700175 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700176 mDebugInSwapBuffers(0),
177 mLastSwapBufferTime(0),
178 mDebugInTransaction(0),
179 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700180 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700181 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800182 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000183 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700184 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700185 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700186 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800187 mHasPoweredOff(false),
188 mFrameBuckets(),
189 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700190 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800191 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700192 mVrFlingerRequestsDisplay(false),
193 mMainThreadId(std::this_thread::get_id()),
194 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800196 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800197
198 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
199 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
200
201 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
202 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
203
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800204 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
205 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700207 useContextPriority = getBool< ISurfaceFlingerConfigs,
208 &ISurfaceFlingerConfigs::useContextPriority>(false);
209
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700210 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
211 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
212
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700213 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
214 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
215
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
217 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
218
Steven Thomas050b2c82017-03-06 11:45:16 -0800219 // Vr flinger is only enabled on Daydream ready devices.
220 useVrFlinger = getBool< ISurfaceFlingerConfigs,
221 &ISurfaceFlingerConfigs::useVrFlinger>(false);
222
Fabien Sanglard1971b632017-03-10 14:50:03 -0800223 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
224 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
225
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600226 hasWideColorDisplay =
227 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
228
Saurabh Shahf4174532017-07-13 10:45:07 -0700229 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
230
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 // debugging stuff...
232 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700233
Mathias Agopianb4b17302013-03-20 18:36:41 -0700234 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700235 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 property_get("debug.sf.showupdates", value, "0");
238 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240 property_get("debug.sf.ddms", value, "0");
241 mDebugDDMS = atoi(value);
242 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700243 if (!startDdmConnection()) {
244 // start failed, and DDMS debugging not enabled
245 mDebugDDMS = 0;
246 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700247 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700248 ALOGI_IF(mDebugRegion, "showupdates enabled");
249 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700250
251 property_get("debug.sf.disable_backpressure", value, "0");
252 mPropagateBackpressure = !atoi(value);
253 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700254
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800255 property_get("debug.sf.enable_hwc_vds", value, "0");
256 mUseHwcVirtualDisplays = atoi(value);
257 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800258
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800259 property_get("ro.sf.disable_triple_buffer", value, "1");
260 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800261 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700262
Romain Guy11d63f42017-07-20 12:47:14 -0700263 // We should be reading 'persist.sys.sf.color_saturation' here
264 // but since /data may be encrypted, we need to wait until after vold
265 // comes online to attempt to read the property. The property is
266 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800267
268 if (useTrebleTestingOverride()) {
269 // Without the override SurfaceFlinger cannot connect to HIDL
270 // services that are not listed in the manifests. Considered
271 // deriving the setting from the set service name, but it
272 // would be brittle if the name that's not 'default' is used
273 // for production purposes later on.
274 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800278void SurfaceFlinger::onFirstRef()
279{
280 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800281}
282
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283SurfaceFlinger::~SurfaceFlinger()
284{
Mathias Agopiana4912602012-07-12 14:25:33 -0700285 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
286 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
287 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288}
289
Dan Stozac7014012014-02-14 15:03:43 -0800290void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800291{
292 // the window manager died on us. prepare its eulogy.
293
Andy McFadden13a082e2012-08-24 10:16:42 -0700294 // restore initial conditions (default device unblank, etc)
295 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800296
297 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700298 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800299}
300
Robert Carr1db73f62016-12-21 12:58:51 -0800301static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700302 status_t err = client->initCheck();
303 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800304 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 }
Robert Carr1db73f62016-12-21 12:58:51 -0800306 return nullptr;
307}
308
309sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
310 return initClient(new Client(this));
311}
312
313sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
314 const sp<IGraphicBufferProducer>& gbp) {
315 if (authenticateSurfaceTexture(gbp) == false) {
316 return nullptr;
317 }
318 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
319 if (layer == nullptr) {
320 return nullptr;
321 }
322
323 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324}
325
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700326sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
327 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700328{
329 class DisplayToken : public BBinder {
330 sp<SurfaceFlinger> flinger;
331 virtual ~DisplayToken() {
332 // no more references, this display must be terminated
333 Mutex::Autolock _l(flinger->mStateLock);
334 flinger->mCurrentState.displays.removeItem(this);
335 flinger->setTransactionFlags(eDisplayTransactionNeeded);
336 }
337 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700338 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700339 : flinger(flinger) {
340 }
341 };
342
343 sp<BBinder> token = new DisplayToken(this);
344
345 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700346 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700347 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700348 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700349 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700350 return token;
351}
352
Jesse Hall6c913be2013-08-08 12:15:49 -0700353void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
354 Mutex::Autolock _l(mStateLock);
355
356 ssize_t idx = mCurrentState.displays.indexOfKey(display);
357 if (idx < 0) {
358 ALOGW("destroyDisplay: invalid display token");
359 return;
360 }
361
362 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
363 if (!info.isVirtualDisplay()) {
364 ALOGE("destroyDisplay called for non-virtual display");
365 return;
366 }
Irvelffc9efc2016-07-27 15:16:37 -0700367 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700368 mCurrentState.displays.removeItemsAt(idx);
369 setTransactionFlags(eDisplayTransactionNeeded);
370}
371
Jesse Hall692c7232012-11-08 15:41:56 -0800372void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800373 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800374 ALOGW_IF(mBuiltinDisplays[type],
375 "Overwriting display token for display type %d", type);
376 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800377 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700378 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800379 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700380 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800381}
382
Mathias Agopiane57f2922012-08-09 16:29:12 -0700383sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700384 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700385 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
386 return NULL;
387 }
Jesse Hall692c7232012-11-08 15:41:56 -0800388 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700389}
390
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800391void SurfaceFlinger::bootFinished()
392{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700393 if (mStartPropertySetThread->join() != NO_ERROR) {
394 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800395 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396 const nsecs_t now = systemTime();
397 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000398 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700399
400 // wait patiently for the window manager death
401 const String16 name("window");
402 sp<IBinder> window(defaultServiceManager()->getService(name));
403 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700404 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700405 }
406
Steven Thomas050b2c82017-03-06 11:45:16 -0800407 if (mVrFlinger) {
408 mVrFlinger->OnBootFinished();
409 }
410
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700411 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700412 // formerly we would just kill the process, but we now ask it to exit so it
413 // can choose where to stop the animation.
414 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700415
416 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
417 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
418 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700419
Romain Guyc53d3552017-07-20 18:49:46 -0700420 sp<LambdaMessage> bootFinished = new LambdaMessage([&]() {
421 mBootFinished = true;
422
Romain Guy11d63f42017-07-20 12:47:14 -0700423 readPersistentProperties();
Romain Guyc53d3552017-07-20 18:49:46 -0700424
425#ifdef USE_HWC2
426 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
427 if (hw->getWideColorSupport()) {
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -0600428 hw->setCompositionDataSpace(HAL_DATASPACE_V0_SRGB);
Romain Guyc53d3552017-07-20 18:49:46 -0700429 setActiveColorModeInternal(hw, HAL_COLOR_MODE_SRGB);
430 }
431#endif
Romain Guy11d63f42017-07-20 12:47:14 -0700432 });
Romain Guyc53d3552017-07-20 18:49:46 -0700433 postMessageAsync(bootFinished);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434}
435
Mathias Agopian3f844832013-08-07 21:24:32 -0700436void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700437 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700438 RenderEngine& engine;
439 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700440 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700441 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
442 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700443 }
444 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700445 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700446 return true;
447 }
448 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700449 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700450}
451
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452class DispSyncSource : public VSyncSource, private DispSync::Callback {
453public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700454 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000455 const char* name) :
456 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700457 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700458 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000459 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
460 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700461 mDispSync(dispSync),
462 mCallbackMutex(),
463 mCallback(),
464 mVsyncMutex(),
465 mPhaseOffset(phaseOffset),
466 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700467
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700468 virtual ~DispSyncSource() {}
469
470 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700471 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700472 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000473 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474 static_cast<DispSync::Callback*>(this));
475 if (err != NO_ERROR) {
476 ALOGE("error registering vsync callback: %s (%d)",
477 strerror(-err), err);
478 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700479 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 } else {
481 status_t err = mDispSync->removeEventListener(
482 static_cast<DispSync::Callback*>(this));
483 if (err != NO_ERROR) {
484 ALOGE("error unregistering vsync callback: %s (%d)",
485 strerror(-err), err);
486 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700487 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700488 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700489 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700490 }
491
492 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700493 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700494 mCallback = callback;
495 }
496
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700497 virtual void setPhaseOffset(nsecs_t phaseOffset) {
498 Mutex::Autolock lock(mVsyncMutex);
499
500 // Normalize phaseOffset to [0, period)
501 auto period = mDispSync->getPeriod();
502 phaseOffset %= period;
503 if (phaseOffset < 0) {
504 // If we're here, then phaseOffset is in (-period, 0). After this
505 // operation, it will be in (0, period)
506 phaseOffset += period;
507 }
508 mPhaseOffset = phaseOffset;
509
510 // If we're not enabled, we don't need to mess with the listeners
511 if (!mEnabled) {
512 return;
513 }
514
515 // Remove the listener with the old offset
516 status_t err = mDispSync->removeEventListener(
517 static_cast<DispSync::Callback*>(this));
518 if (err != NO_ERROR) {
519 ALOGE("error unregistering vsync callback: %s (%d)",
520 strerror(-err), err);
521 }
522
523 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000524 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700525 static_cast<DispSync::Callback*>(this));
526 if (err != NO_ERROR) {
527 ALOGE("error registering vsync callback: %s (%d)",
528 strerror(-err), err);
529 }
530 }
531
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532private:
533 virtual void onDispSyncEvent(nsecs_t when) {
534 sp<VSyncSource::Callback> callback;
535 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700536 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700537 callback = mCallback;
538
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700539 if (mTraceVsync) {
540 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700541 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700542 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700543 }
544
545 if (callback != NULL) {
546 callback->onVSyncEvent(when);
547 }
548 }
549
Tim Murray4a4e4a22016-04-19 16:29:23 +0000550 const char* const mName;
551
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552 int mValue;
553
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700554 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700555 const String8 mVsyncOnLabel;
556 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700557
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700558 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700559
560 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700561 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700562
563 Mutex mVsyncMutex; // Protects the following
564 nsecs_t mPhaseOffset;
565 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700566};
567
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700568class InjectVSyncSource : public VSyncSource {
569public:
570 InjectVSyncSource() {}
571
572 virtual ~InjectVSyncSource() {}
573
574 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
575 std::lock_guard<std::mutex> lock(mCallbackMutex);
576 mCallback = callback;
577 }
578
579 virtual void onInjectSyncEvent(nsecs_t when) {
580 std::lock_guard<std::mutex> lock(mCallbackMutex);
581 mCallback->onVSyncEvent(when);
582 }
583
584 virtual void setVSyncEnabled(bool) {}
585 virtual void setPhaseOffset(nsecs_t) {}
586
587private:
588 std::mutex mCallbackMutex; // Protects the following
589 sp<VSyncSource::Callback> mCallback;
590};
591
Wei Wangf9b05ee2017-07-19 20:59:39 -0700592// Do not call property_set on main thread which will be blocked by init
593// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700594void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700595 ALOGI( "SurfaceFlinger's main thread ready to run. "
596 "Initializing graphics H/W...");
597
Romain Guyc53d3552017-07-20 18:49:46 -0700598 ALOGI("Phase offset NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900599
Steven Thomasb02664d2017-07-26 18:48:28 -0700600 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800601
Steven Thomasb02664d2017-07-26 18:48:28 -0700602 // initialize EGL for the default display
603 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
604 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800605
Steven Thomasb02664d2017-07-26 18:48:28 -0700606 // start the EventThread
607 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
608 vsyncPhaseOffsetNs, true, "app");
609 mEventThread = new EventThread(vsyncSrc, *this, false);
610 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
611 sfVsyncPhaseOffsetNs, true, "sf");
612 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
613 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800614
Steven Thomasb02664d2017-07-26 18:48:28 -0700615 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
616 struct sched_param param = {0};
617 param.sched_priority = 2;
618 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
619 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
620 }
621 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
622 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623 }
624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 // Get a RenderEngine for the given display / config (can't fail)
626 mRenderEngine = RenderEngine::create(mEGLDisplay,
627 HAL_PIXEL_FORMAT_RGBA_8888,
628 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800629
Steven Thomasb02664d2017-07-26 18:48:28 -0700630 // retrieve the EGL context that was selected/created
631 mEGLContext = mRenderEngine->getEGLContext();
632
633 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
634 "couldn't create EGLContext");
635
636 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
637 "Starting with vr flinger active is not currently supported.");
638 mHwc.reset(new HWComposer(mHwcServiceName));
639 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800640
Steven Thomas050b2c82017-03-06 11:45:16 -0800641 if (useVrFlinger) {
642 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700643 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800644 mVrFlingerRequestsDisplay = requestDisplay;
645 signalTransaction();
646 };
647 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
648 vrFlingerRequestDisplayCallback);
649 if (!mVrFlinger) {
650 ALOGE("Failed to start vrflinger");
651 }
652 }
653
Jamie Gennisd1700752013-10-14 12:22:52 -0700654 mEventControlThread = new EventControlThread(this);
655 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
656
Mathias Agopian92a979a2012-08-02 18:32:23 -0700657 // initialize our drawing state
658 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700659
Andy McFadden13a082e2012-08-24 10:16:42 -0700660 // set initial conditions (e.g. unblank default device)
661 initializeDisplays();
662
Dan Stoza4e637772016-07-28 13:31:51 -0700663 mRenderEngine->primeCache();
664
Wei Wangf9b05ee2017-07-19 20:59:39 -0700665 // Inform native graphics APIs whether the present timestamp is supported:
666 if (getHwComposer().hasCapability(
667 HWC2::Capability::PresentFenceIsNotReliable)) {
668 mStartPropertySetThread = new StartPropertySetThread(false);
669 } else {
670 mStartPropertySetThread = new StartPropertySetThread(true);
671 }
672
673 if (mStartPropertySetThread->Start() != NO_ERROR) {
674 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800675 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800676
Dan Stoza9e56aa02015-11-02 13:00:03 -0800677 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700678}
679
Romain Guy11d63f42017-07-20 12:47:14 -0700680void SurfaceFlinger::readPersistentProperties() {
681 char value[PROPERTY_VALUE_MAX];
682
683 property_get("persist.sys.sf.color_saturation", value, "1.0");
684 mSaturation = atof(value);
685 ALOGV("Saturation is set to %.2f", mSaturation);
686}
687
Mathias Agopiana67e4182012-06-19 17:26:12 -0700688void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800689 // Start boot animation service by setting a property mailbox
690 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700691 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800692 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700693 if (mStartPropertySetThread->join() != NO_ERROR) {
694 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800695 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700696}
697
Mathias Agopian875d8e12013-06-07 15:35:48 -0700698size_t SurfaceFlinger::getMaxTextureSize() const {
699 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700700}
701
Mathias Agopian875d8e12013-06-07 15:35:48 -0700702size_t SurfaceFlinger::getMaxViewportDims() const {
703 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700704}
705
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800706// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800707
Jamie Gennis582270d2011-08-17 18:19:00 -0700708bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800709 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800710 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800711 return authenticateSurfaceTextureLocked(bufferProducer);
712}
713
714bool SurfaceFlinger::authenticateSurfaceTextureLocked(
715 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800716 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700717 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800718}
719
Brian Anderson6b376712017-04-04 10:51:39 -0700720status_t SurfaceFlinger::getSupportedFrameTimestamps(
721 std::vector<FrameEvent>* outSupported) const {
722 *outSupported = {
723 FrameEvent::REQUESTED_PRESENT,
724 FrameEvent::ACQUIRE,
725 FrameEvent::LATCH,
726 FrameEvent::FIRST_REFRESH_START,
727 FrameEvent::LAST_REFRESH_START,
728 FrameEvent::GPU_COMPOSITION_DONE,
729 FrameEvent::DEQUEUE_READY,
730 FrameEvent::RELEASE,
731 };
732 if (!getHwComposer().hasCapability(
733 HWC2::Capability::PresentFenceIsNotReliable)) {
734 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
735 }
736 return NO_ERROR;
737}
738
Dan Stoza7f7da322014-05-02 15:26:25 -0700739status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
740 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700741 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700742 return BAD_VALUE;
743 }
744
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500745 if (!display.get())
746 return NAME_NOT_FOUND;
747
Jesse Hall692c7232012-11-08 15:41:56 -0800748 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700749 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800750 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700751 type = i;
752 break;
753 }
754 }
755
756 if (type < 0) {
757 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700758 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759
Mathias Agopian8b736f12012-08-13 17:54:26 -0700760 // TODO: Not sure if display density should handled by SF any longer
761 class Density {
762 static int getDensityFromProperty(char const* propName) {
763 char property[PROPERTY_VALUE_MAX];
764 int density = 0;
765 if (property_get(propName, property, NULL) > 0) {
766 density = atoi(property);
767 }
768 return density;
769 }
770 public:
771 static int getEmuDensity() {
772 return getDensityFromProperty("qemu.sf.lcd_density"); }
773 static int getBuildDensity() {
774 return getDensityFromProperty("ro.sf.lcd_density"); }
775 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700776
Dan Stoza7f7da322014-05-02 15:26:25 -0700777 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700778
Dan Stoza9e56aa02015-11-02 13:00:03 -0800779 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700780 DisplayInfo info = DisplayInfo();
781
Dan Stoza9e56aa02015-11-02 13:00:03 -0800782 float xdpi = hwConfig->getDpiX();
783 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700784
785 if (type == DisplayDevice::DISPLAY_PRIMARY) {
786 // The density of the device is provided by a build property
787 float density = Density::getBuildDensity() / 160.0f;
788 if (density == 0) {
789 // the build doesn't provide a density -- this is wrong!
790 // use xdpi instead
791 ALOGE("ro.sf.lcd_density must be defined as a build property");
792 density = xdpi / 160.0f;
793 }
794 if (Density::getEmuDensity()) {
795 // if "qemu.sf.lcd_density" is specified, it overrides everything
796 xdpi = ydpi = density = Density::getEmuDensity();
797 density /= 160.0f;
798 }
799 info.density = density;
800
801 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000802 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
803 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700804 } else {
805 // TODO: where should this value come from?
806 static const int TV_DENSITY = 213;
807 info.density = TV_DENSITY / 160.0f;
808 info.orientation = 0;
809 }
810
Dan Stoza9e56aa02015-11-02 13:00:03 -0800811 info.w = hwConfig->getWidth();
812 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 info.xdpi = xdpi;
814 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900816 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800817
Andy McFadden91b2ca82014-06-13 14:04:23 -0700818 // This is how far in advance a buffer must be queued for
819 // presentation at a given time. If you want a buffer to appear
820 // on the screen at time N, you must submit the buffer before
821 // (N - presentationDeadline).
822 //
823 // Normally it's one full refresh period (to give SF a chance to
824 // latch the buffer), but this can be reduced by configuring a
825 // DispSync offset. Any additional delays introduced by the hardware
826 // composer or panel must be accounted for here.
827 //
828 // We add an additional 1ms to allow for processing time and
829 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800831 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700832
833 // All non-virtual displays are currently considered secure.
834 info.secure = true;
835
Michael Wright28f24d02016-07-12 13:30:53 -0700836 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700837 }
838
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 return NO_ERROR;
840}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700841
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800842status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700843 DisplayStatInfo* stats) {
844 if (stats == NULL) {
845 return BAD_VALUE;
846 }
847
848 // FIXME for now we always return stats for the primary display
849 memset(stats, 0, sizeof(*stats));
850 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
851 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
852 return NO_ERROR;
853}
854
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700855int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800856 if (display == NULL) {
857 ALOGE("%s : display is NULL", __func__);
858 return BAD_VALUE;
859 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700860
861 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700862 if (device != NULL) {
863 return device->getActiveConfig();
864 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700865
Dan Stoza24a42e92015-03-09 10:04:11 -0700866 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700867}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700868
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700869void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
870 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
871 this);
872 int32_t type = hw->getDisplayType();
873 int currentMode = hw->getActiveConfig();
874
875 if (mode == currentMode) {
876 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
877 return;
878 }
879
880 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
881 ALOGW("Trying to set config for virtual display");
882 return;
883 }
884
885 hw->setActiveConfig(mode);
886 getHwComposer().setActiveConfig(type, mode);
887}
888
889status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
890 class MessageSetActiveConfig: public MessageBase {
891 SurfaceFlinger& mFlinger;
892 sp<IBinder> mDisplay;
893 int mMode;
894 public:
895 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
896 int mode) :
897 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
898 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700899 Vector<DisplayInfo> configs;
900 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700901 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700902 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700903 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700904 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700905 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700906 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
907 if (hw == NULL) {
908 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700909 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700910 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
911 ALOGW("Attempt to set active config = %d for virtual display",
912 mMode);
913 } else {
914 mFlinger.setActiveConfigInternal(hw, mMode);
915 }
916 return true;
917 }
918 };
919 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
920 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700921 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700922}
Michael Wright28f24d02016-07-12 13:30:53 -0700923status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
924 Vector<android_color_mode_t>* outColorModes) {
925 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
926 return BAD_VALUE;
927 }
928
929 if (!display.get()) {
930 return NAME_NOT_FOUND;
931 }
932
933 int32_t type = NAME_NOT_FOUND;
934 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
935 if (display == mBuiltinDisplays[i]) {
936 type = i;
937 break;
938 }
939 }
940
941 if (type < 0) {
942 return type;
943 }
944
945 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
946 outColorModes->clear();
947 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
948
949 return NO_ERROR;
950}
951
952android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700953 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700954 if (device != nullptr) {
955 return device->getActiveColorMode();
956 }
957 return static_cast<android_color_mode_t>(BAD_VALUE);
958}
959
960void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
961 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700962 int32_t type = hw->getDisplayType();
963 android_color_mode_t currentMode = hw->getActiveColorMode();
964
965 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700966 return;
967 }
968
969 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
970 ALOGW("Trying to set config for virtual display");
971 return;
972 }
973
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600974 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
975 hw->getDisplayType());
976
Michael Wright28f24d02016-07-12 13:30:53 -0700977 hw->setActiveColorMode(mode);
978 getHwComposer().setActiveColorMode(type, mode);
979}
980
981
982status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
983 android_color_mode_t colorMode) {
984 class MessageSetActiveColorMode: public MessageBase {
985 SurfaceFlinger& mFlinger;
986 sp<IBinder> mDisplay;
987 android_color_mode_t mMode;
988 public:
989 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
990 android_color_mode_t mode) :
991 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
992 virtual bool handler() {
993 Vector<android_color_mode_t> modes;
994 mFlinger.getDisplayColorModes(mDisplay, &modes);
995 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
996 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600997 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
998 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700999 return true;
1000 }
1001 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1002 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001003 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1004 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001005 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001006 ALOGW("Attempt to set active color mode %s %d for virtual display",
1007 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001008 } else {
1009 mFlinger.setActiveColorModeInternal(hw, mMode);
1010 }
1011 return true;
1012 }
1013 };
1014 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1015 postMessageSync(msg);
1016 return NO_ERROR;
1017}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001018
Svetoslavd85084b2014-03-20 10:28:31 -07001019status_t SurfaceFlinger::clearAnimationFrameStats() {
1020 Mutex::Autolock _l(mStateLock);
1021 mAnimFrameTracker.clearStats();
1022 return NO_ERROR;
1023}
1024
1025status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1026 Mutex::Autolock _l(mStateLock);
1027 mAnimFrameTracker.getStats(outStats);
1028 return NO_ERROR;
1029}
1030
Dan Stozac4f471e2016-03-24 09:31:08 -07001031status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1032 HdrCapabilities* outCapabilities) const {
1033 Mutex::Autolock _l(mStateLock);
1034
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001035 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001036 if (displayDevice == nullptr) {
1037 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1038 return BAD_VALUE;
1039 }
1040
1041 std::unique_ptr<HdrCapabilities> capabilities =
1042 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1043 if (capabilities) {
1044 std::swap(*outCapabilities, *capabilities);
1045 } else {
1046 return BAD_VALUE;
1047 }
1048
1049 return NO_ERROR;
1050}
1051
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001052status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1053 if (enable == mInjectVSyncs) {
1054 return NO_ERROR;
1055 }
1056
1057 if (enable) {
1058 mInjectVSyncs = enable;
1059 ALOGV("VSync Injections enabled");
1060 if (mVSyncInjector.get() == nullptr) {
1061 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001062 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001063 }
1064 mEventQueue.setEventThread(mInjectorEventThread);
1065 } else {
1066 mInjectVSyncs = enable;
1067 ALOGV("VSync Injections disabled");
1068 mEventQueue.setEventThread(mSFEventThread);
1069 mVSyncInjector.clear();
1070 }
1071 return NO_ERROR;
1072}
1073
1074status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1075 if (!mInjectVSyncs) {
1076 ALOGE("VSync Injections not enabled");
1077 return BAD_VALUE;
1078 }
1079 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1080 ALOGV("Injecting VSync inside SurfaceFlinger");
1081 mVSyncInjector->onInjectSyncEvent(when);
1082 }
1083 return NO_ERROR;
1084}
1085
Kalle Raitaa099a242017-01-11 11:17:29 -08001086status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1087 IPCThreadState* ipc = IPCThreadState::self();
1088 const int pid = ipc->getCallingPid();
1089 const int uid = ipc->getCallingUid();
1090 if ((uid != AID_SHELL) &&
1091 !PermissionCache::checkPermission(sDump, pid, uid)) {
1092 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1093 return PERMISSION_DENIED;
1094 }
1095
1096 // Try to acquire a lock for 1s, fail gracefully
1097 const status_t err = mStateLock.timedLock(s2ns(1));
1098 const bool locked = (err == NO_ERROR);
1099 if (!locked) {
1100 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1101 return TIMED_OUT;
1102 }
1103
1104 outLayers->clear();
1105 mCurrentState.traverseInZOrder([&](Layer* layer) {
1106 outLayers->push_back(layer->getLayerDebugInfo());
1107 });
1108
1109 mStateLock.unlock();
1110 return NO_ERROR;
1111}
1112
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001113// ----------------------------------------------------------------------------
1114
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001115sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1116 ISurfaceComposer::VsyncSource vsyncSource) {
1117 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1118 return mSFEventThread->createEventConnection();
1119 } else {
1120 return mEventThread->createEventConnection();
1121 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001122}
1123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001124// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001125
1126void SurfaceFlinger::waitForEvent() {
1127 mEventQueue.waitMessage();
1128}
1129
1130void SurfaceFlinger::signalTransaction() {
1131 mEventQueue.invalidate();
1132}
1133
1134void SurfaceFlinger::signalLayerUpdate() {
1135 mEventQueue.invalidate();
1136}
1137
1138void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001139 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001140 mEventQueue.refresh();
1141}
1142
1143status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001144 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001145 return mEventQueue.postMessage(msg, reltime);
1146}
1147
1148status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001149 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001150 status_t res = mEventQueue.postMessage(msg, reltime);
1151 if (res == NO_ERROR) {
1152 msg->wait();
1153 }
1154 return res;
1155}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001156
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001157void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001158 do {
1159 waitForEvent();
1160 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001161}
1162
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001163void SurfaceFlinger::enableHardwareVsync() {
1164 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001165 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001166 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001167 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1168 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001169 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001170 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001171}
1172
Jesse Hall948fe0c2013-10-14 12:56:09 -07001173void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001174 Mutex::Autolock _l(mHWVsyncLock);
1175
Jesse Hall948fe0c2013-10-14 12:56:09 -07001176 if (makeAvailable) {
1177 mHWVsyncAvailable = true;
1178 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001179 // Hardware vsync is not currently available, so abort the resync
1180 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001181 return;
1182 }
1183
Dan Stoza9e56aa02015-11-02 13:00:03 -08001184 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1185 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186
1187 mPrimaryDispSync.reset();
1188 mPrimaryDispSync.setPeriod(period);
1189
1190 if (!mPrimaryHWVsyncEnabled) {
1191 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001192 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1193 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194 mPrimaryHWVsyncEnabled = true;
1195 }
1196}
1197
Jesse Hall948fe0c2013-10-14 12:56:09 -07001198void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001199 Mutex::Autolock _l(mHWVsyncLock);
1200 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001201 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1202 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001203 mPrimaryDispSync.endResync();
1204 mPrimaryHWVsyncEnabled = false;
1205 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001206 if (makeUnavailable) {
1207 mHWVsyncAvailable = false;
1208 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001209}
1210
Tim Murray4a4e4a22016-04-19 16:29:23 +00001211void SurfaceFlinger::resyncWithRateLimit() {
1212 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001213
1214 // No explicit locking is needed here since EventThread holds a lock while calling this method
1215 static nsecs_t sLastResyncAttempted = 0;
1216 const nsecs_t now = systemTime();
1217 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001218 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001219 }
Dan Stoza57164302017-05-08 14:03:54 -07001220 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001221}
1222
Steven Thomasb02664d2017-07-26 18:48:28 -07001223void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1224 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001225 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001226 // Ignore any vsyncs from a previous hardware composer.
1227 if (sequenceId != mComposerSequenceId) {
1228 return;
1229 }
1230
1231 int32_t type;
1232 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001233 return;
1234 }
1235
Jamie Gennisd1700752013-10-14 12:22:52 -07001236 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001237
Jamie Gennisd1700752013-10-14 12:22:52 -07001238 { // Scope for the lock
1239 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001240 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001241 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001242 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001243 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001244
1245 if (needsHwVsync) {
1246 enableHardwareVsync();
1247 } else {
1248 disableHardwareVsync(false);
1249 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001250}
1251
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001252void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001253 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001254 *compositorTiming = mCompositorTiming;
1255}
1256
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001257void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001258 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001259 wp<IBinder> token = mBuiltinDisplays[type];
1260
1261 // All non-virtual displays are currently considered secure.
1262 const bool isSecure = true;
1263
1264 sp<IGraphicBufferProducer> producer;
1265 sp<IGraphicBufferConsumer> consumer;
1266 BufferQueue::createBufferQueue(&producer, &consumer);
1267
1268 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1269
1270 bool hasWideColorModes = false;
1271 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1272 for (android_color_mode_t colorMode : modes) {
1273 switch (colorMode) {
1274 case HAL_COLOR_MODE_DISPLAY_P3:
1275 case HAL_COLOR_MODE_ADOBE_RGB:
1276 case HAL_COLOR_MODE_DCI_P3:
1277 hasWideColorModes = true;
1278 break;
1279 default:
1280 break;
1281 }
1282 }
1283 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1284 token, fbs, producer, mRenderEngine->getEGLConfig(),
1285 hasWideColorModes && hasWideColorDisplay);
1286 mDisplays.add(token, hw);
Romain Guyc53d3552017-07-20 18:49:46 -07001287 setActiveColorModeInternal(hw, HAL_COLOR_MODE_NATIVE);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001288 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001289
1290 // Add the primary display token to mDrawingState so we don't try to
1291 // recreate the DisplayDevice for the primary display.
1292 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1293
1294 // make the GLContext current so that we can create textures when creating
1295 // Layers (which may happens before we render something)
1296 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001297}
1298
Steven Thomasb02664d2017-07-26 18:48:28 -07001299void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1300 hwc2_display_t display, HWC2::Connection connection,
1301 bool primaryDisplay) {
1302 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1303 sequenceId, display,
1304 connection == HWC2::Connection::Connected ?
1305 "connected" : "disconnected",
1306 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001307
Steven Thomasb02664d2017-07-26 18:48:28 -07001308 // Only lock if we're not on the main thread. This function is normally
1309 // called on a hwbinder thread, but for the primary display it's called on
1310 // the main thread with the state lock already held, so don't attempt to
1311 // acquire it here.
1312 ConditionalLock lock(mStateLock,
1313 std::this_thread::get_id() != mMainThreadId);
1314
1315 if (primaryDisplay) {
1316 mHwc->onHotplug(display, connection);
1317 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1318 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001319 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001320 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001321 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001322 if (sequenceId != mComposerSequenceId) {
1323 return;
1324 }
1325 if (mHwc->isUsingVrComposer()) {
1326 ALOGE("External displays are not supported by the vr hardware composer.");
1327 return;
1328 }
1329 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001330 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001331 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001332 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001333 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001334 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1335 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001336 }
1337 setTransactionFlags(eDisplayTransactionNeeded);
1338
Andy McFadden9e9689c2012-10-10 18:17:51 -07001339 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001340 }
Mathias Agopian86303202012-07-24 22:46:10 -07001341}
1342
Steven Thomasb02664d2017-07-26 18:48:28 -07001343void SurfaceFlinger::onRefreshReceived(int sequenceId,
1344 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001345 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 if (sequenceId != mComposerSequenceId) {
1347 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001348 }
Steven Thomasb02664d2017-07-26 18:48:28 -07001349 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001350}
1351
Dan Stoza9e56aa02015-11-02 13:00:03 -08001352void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001353 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001354 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001355 getHwComposer().setVsyncEnabled(disp,
1356 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001357}
1358
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001360void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001361 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001362 // Clear the drawing state so that the logic inside of
1363 // handleTransactionLocked will fire. It will determine the delta between
1364 // mCurrentState and mDrawingState and re-apply all changes when we make the
1365 // transition.
1366 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001368 mDisplays.clear();
1369}
1370
Steven Thomas050b2c82017-03-06 11:45:16 -08001371void SurfaceFlinger::updateVrFlinger() {
1372 if (!mVrFlinger)
1373 return;
1374 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1375 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001376 return;
1377 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001378
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1380 ALOGE("Vr flinger is only supported for remote hardware composer"
1381 " service connections. Ignoring request to transition to vr"
1382 " flinger.");
1383 mVrFlingerRequestsDisplay = false;
1384 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001385 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001386
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001387 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001388
Steven Thomasb02664d2017-07-26 18:48:28 -07001389 int currentDisplayPowerMode = getDisplayDeviceLocked(
1390 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001391
Steven Thomasb02664d2017-07-26 18:48:28 -07001392 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001394 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001395
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 resetDisplayState();
1397 mHwc.reset(); // Delete the current instance before creating the new one
1398 mHwc.reset(new HWComposer(
1399 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1400 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001401
Steven Thomasb02664d2017-07-26 18:48:28 -07001402 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1403 "Switched to non-remote hardware composer");
1404
1405 if (vrFlingerRequestsDisplay) {
1406 mVrFlinger->GrantDisplayOwnership();
1407 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001409 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001410
1411 mVisibleRegionsDirty = true;
1412 invalidateHwcGeometry();
1413
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001414 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1416 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1417 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001418
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 // Reset the timing values to account for the period of the swapped in HWC
1420 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1421 const nsecs_t period = activeConfig->getVsyncPeriod();
1422 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001423
Steven Thomasb02664d2017-07-26 18:48:28 -07001424 // Use phase of 0 since phase is not known.
1425 // Use latency of 0, which will snap to the ideal latency.
1426 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001427
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001428 android_atomic_or(1, &mRepaintEverything);
1429 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001430}
1431
Mathias Agopian4fec8732012-06-29 14:12:52 -07001432void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001433 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001434 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001435 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001436 bool frameMissed = !mHadClientComposition &&
1437 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001438 (mPreviousPresentFence->getSignalTime() ==
1439 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001440 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001441 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001442 signalLayerUpdate();
1443 break;
1444 }
1445
Steven Thomas050b2c82017-03-06 11:45:16 -08001446 // Now that we're going to make it to the handleMessageTransaction()
1447 // call below it's safe to call updateVrFlinger(), which will
1448 // potentially trigger a display handoff.
1449 updateVrFlinger();
1450
Dan Stoza6b9454d2014-11-07 16:00:59 -08001451 bool refreshNeeded = handleMessageTransaction();
1452 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001453 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001454 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001455 // Signal a refresh if a transaction modified the window state,
1456 // a new buffer was latched, or if HWC has requested a full
1457 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001458 signalRefresh();
1459 }
1460 break;
1461 }
1462 case MessageQueue::REFRESH: {
1463 handleMessageRefresh();
1464 break;
1465 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001466 }
1467}
1468
Dan Stoza6b9454d2014-11-07 16:00:59 -08001469bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001470 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001471 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001472 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001473 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001474 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001475 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001476}
1477
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001479 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001480 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001481}
1482
1483void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001484 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001485
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001486 mRefreshPending = false;
1487
Pablo Ceballos40845df2016-01-25 17:41:15 -08001488 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001489
Brian Andersond6927fb2016-07-23 23:37:30 -07001490 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001491 rebuildLayerStacks();
1492 setUpHWComposer();
1493 doDebugFlashRegions();
1494 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001495 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001496
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001497 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001498
1499 mHadClientComposition = false;
1500 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1501 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1502 mHadClientComposition = mHadClientComposition ||
1503 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1504 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001505
Dan Stoza9e56aa02015-11-02 13:00:03 -08001506 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001507}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001508
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509void SurfaceFlinger::doDebugFlashRegions()
1510{
1511 // is debugging enabled
1512 if (CC_LIKELY(!mDebugRegion))
1513 return;
1514
1515 const bool repaintEverything = mRepaintEverything;
1516 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1517 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001518 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519 // transform the dirty region into this screen's coordinate space
1520 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1521 if (!dirtyRegion.isEmpty()) {
1522 // redraw the whole screen
1523 doComposeSurfaces(hw, Region(hw->bounds()));
1524
1525 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001526 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001527 RenderEngine& engine(getRenderEngine());
1528 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1529
Mathias Agopianda27af92012-09-13 18:17:13 -07001530 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001531 }
1532 }
1533 }
1534
1535 postFramebuffer();
1536
1537 if (mDebugRegion > 1) {
1538 usleep(mDebugRegion * 1000);
1539 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001540
Dan Stoza9e56aa02015-11-02 13:00:03 -08001541 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001542 auto& displayDevice = mDisplays[displayId];
1543 if (!displayDevice->isDisplayOn()) {
1544 continue;
1545 }
1546
1547 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001548 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1549 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001550 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001551}
1552
Brian Andersond6927fb2016-07-23 23:37:30 -07001553void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001554{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001555 ATRACE_CALL();
1556 ALOGV("preComposition");
1557
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001559 mDrawingState.traverseInZOrder([&](Layer* layer) {
1560 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001561 needExtraInvalidate = true;
1562 }
Robert Carr2047fae2016-11-28 14:09:09 -08001563 });
1564
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565 if (needExtraInvalidate) {
1566 signalLayerUpdate();
1567 }
1568}
1569
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001570void SurfaceFlinger::updateCompositorTiming(
1571 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1572 std::shared_ptr<FenceTime>& presentFenceTime) {
1573 // Update queue of past composite+present times and determine the
1574 // most recently known composite to present latency.
1575 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1576 nsecs_t compositeToPresentLatency = -1;
1577 while (!mCompositePresentTimes.empty()) {
1578 CompositePresentTime& cpt = mCompositePresentTimes.front();
1579 // Cached values should have been updated before calling this method,
1580 // which helps avoid duplicate syscalls.
1581 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1582 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1583 break;
1584 }
1585 compositeToPresentLatency = displayTime - cpt.composite;
1586 mCompositePresentTimes.pop();
1587 }
1588
1589 // Don't let mCompositePresentTimes grow unbounded, just in case.
1590 while (mCompositePresentTimes.size() > 16) {
1591 mCompositePresentTimes.pop();
1592 }
1593
Brian Andersond0010582017-03-07 13:20:31 -08001594 setCompositorTimingSnapped(
1595 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1596}
1597
1598void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1599 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001600 // Integer division and modulo round toward 0 not -inf, so we need to
1601 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001602 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001603 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1604 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1605
Brian Andersond0010582017-03-07 13:20:31 -08001606 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1607 if (idealLatency <= 0) {
1608 idealLatency = vsyncInterval;
1609 }
1610
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001611 // Snap the latency to a value that removes scheduling jitter from the
1612 // composition and present times, which often have >1ms of jitter.
1613 // Reducing jitter is important if an app attempts to extrapolate
1614 // something (such as user input) to an accurate diasplay time.
1615 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1616 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001617 nsecs_t bias = vsyncInterval / 2;
1618 int64_t extraVsyncs =
1619 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1620 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1621 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001622
Brian Andersond0010582017-03-07 13:20:31 -08001623 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001624 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1625 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001626 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001627}
1628
1629void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001630{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001631 ATRACE_CALL();
1632 ALOGV("postComposition");
1633
Brian Anderson3546a3f2016-07-14 11:51:14 -07001634 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001635 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001636 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001637 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001638 }
1639
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001640 // |mStateLock| not needed as we are on the main thread
1641 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001642
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001643 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001644 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1645 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1646 glCompositionDoneFenceTime =
1647 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1648 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1649 } else {
1650 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1651 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001652
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001653 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001654 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1655 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1656 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001657
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001658 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1659 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1660
1661 // We use the refreshStartTime which might be sampled a little later than
1662 // when we started doing work for this frame, but that should be okay
1663 // since updateCompositorTiming has snapping logic.
1664 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001665 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001666 CompositorTiming compositorTiming;
1667 {
1668 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1669 compositorTiming = mCompositorTiming;
1670 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001671
Robert Carr2047fae2016-11-28 14:09:09 -08001672 mDrawingState.traverseInZOrder([&](Layer* layer) {
1673 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001674 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001675 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001676 recordBufferingStats(layer->getName().string(),
1677 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001678 }
Robert Carr2047fae2016-11-28 14:09:09 -08001679 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001680
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001681 if (presentFenceTime->isValid()) {
1682 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001683 enableHardwareVsync();
1684 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001685 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001686 }
1687 }
1688
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001689 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001690 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001691 enableHardwareVsync();
1692 }
1693 }
1694
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001695 if (mAnimCompositionPending) {
1696 mAnimCompositionPending = false;
1697
Brian Anderson4e606e32017-03-16 15:34:57 -07001698 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001699 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001700 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001701 } else {
1702 // The HWC doesn't support present fences, so use the refresh
1703 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001704 nsecs_t presentTime =
1705 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001706 mAnimFrameTracker.setActualPresentTime(presentTime);
1707 }
1708 mAnimFrameTracker.advanceFrame();
1709 }
Dan Stozab90cf072015-03-05 11:05:59 -08001710
1711 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1712 return;
1713 }
1714
1715 nsecs_t currentTime = systemTime();
1716 if (mHasPoweredOff) {
1717 mHasPoweredOff = false;
1718 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001719 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001720 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001721 if (numPeriods < NUM_BUCKETS - 1) {
1722 mFrameBuckets[numPeriods] += elapsedTime;
1723 } else {
1724 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1725 }
1726 mTotalTime += elapsedTime;
1727 }
1728 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001729}
1730
1731void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001732 ATRACE_CALL();
1733 ALOGV("rebuildLayerStacks");
1734
Mathias Agopiancd60f992012-08-16 16:28:27 -07001735 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001736 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1737 ATRACE_CALL();
1738 mVisibleRegionsDirty = false;
1739 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001740
Jeff Sharkey76488112017-02-27 14:15:18 -07001741 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1742 Region opaqueRegion;
1743 Region dirtyRegion;
1744 Vector<sp<Layer>> layersSortedByZ;
1745 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1746 const Transform& tr(displayDevice->getTransform());
1747 const Rect bounds(displayDevice->getBounds());
1748 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001749 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001750
Jeff Sharkey76488112017-02-27 14:15:18 -07001751 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001752 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1753 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001754 Region drawRegion(tr.transform(
1755 layer->visibleNonTransparentRegion));
1756 drawRegion.andSelf(bounds);
1757 if (!drawRegion.isEmpty()) {
1758 layersSortedByZ.add(layer);
1759 } else {
1760 // Clear out the HWC layer if this layer was
1761 // previously visible, but no longer is
Steven Thomasb02664d2017-07-26 18:48:28 -07001762 layer->destroyHwcLayer(
1763 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001764 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001765 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001766 // WM changes displayDevice->layerStack upon sleep/awake.
1767 // Here we make sure we delete the HWC layers even if
1768 // WM changed their layer stack.
Steven Thomasb02664d2017-07-26 18:48:28 -07001769 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001770 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001771 });
1772 }
1773 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1774 displayDevice->undefinedRegion.set(bounds);
1775 displayDevice->undefinedRegion.subtractSelf(
1776 tr.transform(opaqueRegion));
1777 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001778 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001779 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001780}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001781
Romain Guy0147a172017-06-01 13:53:56 -07001782mat4 SurfaceFlinger::computeSaturationMatrix() const {
1783 if (mSaturation == 1.0f) {
1784 return mat4();
1785 }
1786
1787 // Rec.709 luma coefficients
1788 float3 luminance{0.213f, 0.715f, 0.072f};
1789 luminance *= 1.0f - mSaturation;
1790 return mat4(
1791 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1792 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1793 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1794 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1795 );
1796}
1797
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001798// pickColorMode translates a given dataspace into the best available color mode.
1799// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001800android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001801 switch (dataSpace) {
1802 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1803 // system expects.
1804 case HAL_DATASPACE_UNKNOWN:
1805 case HAL_DATASPACE_SRGB:
1806 case HAL_DATASPACE_V0_SRGB:
1807 return HAL_COLOR_MODE_SRGB;
1808 break;
1809
1810 case HAL_DATASPACE_DISPLAY_P3:
1811 return HAL_COLOR_MODE_DISPLAY_P3;
1812 break;
1813
1814 default:
1815 // TODO (courtneygo): Do we want to assert an error here?
1816 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1817 dataSpace);
1818 return HAL_COLOR_MODE_SRGB;
1819 break;
1820 }
1821}
1822
Romain Guy0147a172017-06-01 13:53:56 -07001823android_dataspace SurfaceFlinger::bestTargetDataSpace(
1824 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001825 // Only support sRGB and Display-P3 right now.
1826 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1827 return HAL_DATASPACE_DISPLAY_P3;
1828 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001829 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1830 return HAL_DATASPACE_DISPLAY_P3;
1831 }
1832 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1833 return HAL_DATASPACE_DISPLAY_P3;
1834 }
1835
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001836 return HAL_DATASPACE_V0_SRGB;
1837}
1838
Mathias Agopiancd60f992012-08-16 16:28:27 -07001839void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001840 ATRACE_CALL();
1841 ALOGV("setUpHWComposer");
1842
Jesse Hall028dc8f2013-08-20 16:35:32 -07001843 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001844 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1845 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1846 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1847
1848 // If nothing has changed (!dirty), don't recompose.
1849 // If something changed, but we don't currently have any visible layers,
1850 // and didn't when we last did a composition, then skip it this time.
1851 // The second rule does two things:
1852 // - When all layers are removed from a display, we'll emit one black
1853 // frame, then nothing more until we get new layers.
1854 // - When a display is created with a private layer stack, we won't
1855 // emit any black frames until a layer is added to the layer stack.
1856 bool mustRecompose = dirty && !(empty && wasEmpty);
1857
1858 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1859 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1860 mustRecompose ? "doing" : "skipping",
1861 dirty ? "+" : "-",
1862 empty ? "+" : "-",
1863 wasEmpty ? "+" : "-");
1864
Dan Stoza71433162014-02-04 16:22:36 -08001865 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001866
1867 if (mustRecompose) {
1868 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1869 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001870 }
1871
Dan Stoza9e56aa02015-11-02 13:00:03 -08001872 // build the h/w work list
1873 if (CC_UNLIKELY(mGeometryInvalid)) {
1874 mGeometryInvalid = false;
1875 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1876 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1877 const auto hwcId = displayDevice->getHwcDisplayId();
1878 if (hwcId >= 0) {
1879 const Vector<sp<Layer>>& currentLayers(
1880 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001881 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001882 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001883 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001884 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001885 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001887 }
1888 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001889
Robert Carrae060832016-11-28 10:51:00 -08001890 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001891 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001892 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001893 }
1894 }
1895 }
1896 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 }
Riley Andrews03414a12014-07-01 14:22:59 -07001898
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001899
Romain Guy0147a172017-06-01 13:53:56 -07001900 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001901
Dan Stoza9e56aa02015-11-02 13:00:03 -08001902 // Set the per-frame data
1903 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1904 auto& displayDevice = mDisplays[displayId];
1905 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001906
Dan Stoza9e56aa02015-11-02 13:00:03 -08001907 if (hwcId < 0) {
1908 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001909 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001910 if (colorMatrix != mPreviousColorMatrix) {
1911 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1912 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1913 "display %zd: %d", displayId, result);
1914 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001915 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1916 layer->setPerFrameData(displayDevice);
1917 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001918
1919 if (hasWideColorDisplay) {
1920 android_color_mode newColorMode;
1921 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1922
1923 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1924 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1925 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1926 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1927 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1928 }
1929 newColorMode = pickColorMode(newDataSpace);
1930
Romain Guyc53d3552017-07-20 18:49:46 -07001931 // We want the color mode of the boot animation to match that of the bootloader
1932 // To achieve this we suppress color mode changes until after the boot animation
1933 if (mBootFinished) {
1934 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001935 displayDevice->setCompositionDataSpace(newDataSpace);
Romain Guyc53d3552017-07-20 18:49:46 -07001936 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001937 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 }
1939
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001940 mPreviousColorMatrix = colorMatrix;
1941
Dan Stoza9e56aa02015-11-02 13:00:03 -08001942 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001943 auto& displayDevice = mDisplays[displayId];
1944 if (!displayDevice->isDisplayOn()) {
1945 continue;
1946 }
1947
1948 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1950 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001951 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001952}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001953
Mathias Agopiancd60f992012-08-16 16:28:27 -07001954void SurfaceFlinger::doComposition() {
1955 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 ALOGV("doComposition");
1957
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001958 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001959 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001960 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001961 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001962 // transform the dirty region into this screen's coordinate space
1963 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001964
1965 // repaint the framebuffer (if needed)
1966 doDisplayComposition(hw, dirtyRegion);
1967
Mathias Agopiancd60f992012-08-16 16:28:27 -07001968 hw->dirtyRegion.clear();
1969 hw->flip(hw->swapRegion);
1970 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001971 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001972 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001973 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001974}
1975
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001976void SurfaceFlinger::postFramebuffer()
1977{
Mathias Agopian841cde52012-03-01 15:44:37 -08001978 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001979 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001980
Mathias Agopiana44b0412011-10-16 18:46:35 -07001981 const nsecs_t now = systemTime();
1982 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001983
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1985 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001986 if (!displayDevice->isDisplayOn()) {
1987 continue;
1988 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001989 const auto hwcId = displayDevice->getHwcDisplayId();
1990 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001991 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001992 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001993 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001994 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001995 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1996 sp<Fence> releaseFence = Fence::NO_FENCE;
1997 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1998 releaseFence = displayDevice->getClientTargetAcquireFence();
1999 } else {
2000 auto hwcLayer = layer->getHwcLayer(hwcId);
2001 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002002 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 layer->onLayerDisplayed(releaseFence);
2004 }
2005 if (hwcId >= 0) {
2006 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002007 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002008 }
2009
Mathias Agopiana44b0412011-10-16 18:46:35 -07002010 mLastSwapBufferTime = systemTime() - now;
2011 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002012
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002013 // |mStateLock| not needed as we are on the main thread
2014 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002015 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2016 logFrameStats();
2017 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002018}
2019
Mathias Agopian87baae12012-07-31 12:38:26 -07002020void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002021{
Mathias Agopian841cde52012-03-01 15:44:37 -08002022 ATRACE_CALL();
2023
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002024 // here we keep a copy of the drawing state (that is the state that's
2025 // going to be overwritten by handleTransactionLocked()) outside of
2026 // mStateLock so that the side-effects of the State assignment
2027 // don't happen with mStateLock held (which can cause deadlocks).
2028 State drawingState(mDrawingState);
2029
Mathias Agopianca4d3602011-05-19 15:38:14 -07002030 Mutex::Autolock _l(mStateLock);
2031 const nsecs_t now = systemTime();
2032 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002033
Mathias Agopianca4d3602011-05-19 15:38:14 -07002034 // Here we're guaranteed that some transaction flags are set
2035 // so we can call handleTransactionLocked() unconditionally.
2036 // We call getTransactionFlags(), which will also clear the flags,
2037 // with mStateLock held to guarantee that mCurrentState won't change
2038 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002039
Mathias Agopiane57f2922012-08-09 16:29:12 -07002040 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002041 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002042
Mathias Agopianca4d3602011-05-19 15:38:14 -07002043 mLastTransactionTime = systemTime() - now;
2044 mDebugInTransaction = 0;
2045 invalidateHwcGeometry();
2046 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002047}
2048
Mathias Agopian87baae12012-07-31 12:38:26 -07002049void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002050{
Dan Stoza7dde5992015-05-22 09:51:44 -07002051 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002052 mCurrentState.traverseInZOrder([](Layer* layer) {
2053 layer->notifyAvailableFrames();
2054 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002055
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002056 /*
2057 * Traversal of the children
2058 * (perform the transaction for each of them if needed)
2059 */
2060
Mathias Agopian3559b072012-08-15 13:46:03 -07002061 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002062 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002063 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002064 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002065
2066 const uint32_t flags = layer->doTransaction(0);
2067 if (flags & Layer::eVisibleRegion)
2068 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002069 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002070 }
2071
2072 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002073 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002074 */
2075
Mathias Agopiane57f2922012-08-09 16:29:12 -07002076 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002077 // here we take advantage of Vector's copy-on-write semantics to
2078 // improve performance by skipping the transaction entirely when
2079 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002080 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2081 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002082 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002083 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002084 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002085 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002086
2087 // find the displays that were removed
2088 // (ie: in drawing state but not in current state)
2089 // also handle displays that changed
2090 // (ie: displays that are in both lists)
2091 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002092 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2093 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002094 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002095 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002096 // Call makeCurrent() on the primary display so we can
2097 // be sure that nothing associated with this display
2098 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002099 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002100 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002101 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002102 if (hw != NULL)
2103 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002104 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002105 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002106 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002107 } else {
2108 ALOGW("trying to remove the main display");
2109 }
2110 } else {
2111 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002112 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002113 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002114 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2115 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002116 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002117 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002118 // recreating the DisplayDevice, so we just remove it
2119 // from the drawing state, so that it get re-added
2120 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002121 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002122 if (hw != NULL)
2123 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002124 mDisplays.removeItem(display);
2125 mDrawingState.displays.removeItemsAt(i);
2126 dc--; i--;
2127 // at this point we must loop to the next item
2128 continue;
2129 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002130
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002131 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002132 if (disp != NULL) {
2133 if (state.layerStack != draw[i].layerStack) {
2134 disp->setLayerStack(state.layerStack);
2135 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002136 if ((state.orientation != draw[i].orientation)
2137 || (state.viewport != draw[i].viewport)
2138 || (state.frame != draw[i].frame))
2139 {
2140 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002141 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002142 }
Michael Lentine47e45402014-07-18 15:34:25 -07002143 if (state.width != draw[i].width || state.height != draw[i].height) {
2144 disp->setDisplaySize(state.width, state.height);
2145 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002146 }
2147 }
2148 }
2149
2150 // find displays that were added
2151 // (ie: in current state but not in drawing state)
2152 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002153 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002154 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002155
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002156 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002157 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002158 sp<IGraphicBufferProducer> bqProducer;
2159 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002160 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002161
Dan Stoza9e56aa02015-11-02 13:00:03 -08002162 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002163 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002164 // Virtual displays without a surface are dormant:
2165 // they have external state (layer stack, projection,
2166 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002167 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002168
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002169 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002170 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002171 int width = 0;
2172 int status = state.surface->query(
2173 NATIVE_WINDOW_WIDTH, &width);
2174 ALOGE_IF(status != NO_ERROR,
2175 "Unable to query width (%d)", status);
2176 int height = 0;
2177 status = state.surface->query(
2178 NATIVE_WINDOW_HEIGHT, &height);
2179 ALOGE_IF(status != NO_ERROR,
2180 "Unable to query height (%d)", status);
2181 int intFormat = 0;
2182 status = state.surface->query(
2183 NATIVE_WINDOW_FORMAT, &intFormat);
2184 ALOGE_IF(status != NO_ERROR,
2185 "Unable to query format (%d)", status);
2186 auto format = static_cast<android_pixel_format_t>(
2187 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002188
Dan Stoza8cf150a2016-08-02 10:27:31 -07002189 mHwc->allocateVirtualDisplay(width, height, &format,
2190 &hwcId);
2191 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002192
Dan Stoza5cf424b2016-05-20 14:02:39 -07002193 // TODO: Plumb requested format back up to consumer
2194
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 sp<VirtualDisplaySurface> vds =
2196 new VirtualDisplaySurface(*mHwc,
2197 hwcId, state.surface, bqProducer,
2198 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002199
2200 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002201 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002202 }
2203 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002204 ALOGE_IF(state.surface!=NULL,
2205 "adding a supported display, but rendering "
2206 "surface is provided (%p), ignoring it",
2207 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002208
2209 hwcId = state.type;
2210 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2211 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002212 }
2213
2214 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002215 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002216 sp<DisplayDevice> hw =
2217 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2218 dispSurface, producer,
2219 mRenderEngine->getEGLConfig(),
2220 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002221 hw->setLayerStack(state.layerStack);
2222 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002223 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002224 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002225 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002226 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002227 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002228 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002229 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002230 }
2231 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002232 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002233 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234
Mathias Agopian84300952012-11-21 16:02:13 -08002235 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2236 // The transform hint might have changed for some layers
2237 // (either because a display has changed, or because a layer
2238 // as changed).
2239 //
2240 // Walk through all the layers in currentLayers,
2241 // and update their transform hint.
2242 //
2243 // If a layer is visible only on a single display, then that
2244 // display is used to calculate the hint, otherwise we use the
2245 // default display.
2246 //
2247 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2248 // the hint is set before we acquire a buffer from the surface texture.
2249 //
2250 // NOTE: layer transactions have taken place already, so we use their
2251 // drawing state. However, SurfaceFlinger's own transaction has not
2252 // happened yet, so we must use the current state layer list
2253 // (soon to become the drawing state list).
2254 //
2255 sp<const DisplayDevice> disp;
2256 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002257 bool first = true;
2258 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002259 // NOTE: we rely on the fact that layers are sorted by
2260 // layerStack first (so we don't have to traverse the list
2261 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002262 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002263 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002264 currentlayerStack = layerStack;
2265 // figure out if this layerstack is mirrored
2266 // (more than one display) if so, pick the default display,
2267 // if not, pick the only display it's on.
2268 disp.clear();
2269 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2270 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002271 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002272 if (disp == NULL) {
2273 disp = hw;
2274 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002275 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002276 break;
2277 }
2278 }
2279 }
2280 }
Chet Haase91d25932013-04-11 15:24:55 -07002281 if (disp == NULL) {
2282 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2283 // redraw after transform hint changes. See bug 8508397.
2284
2285 // could be null when this layer is using a layerStack
2286 // that is not visible on any display. Also can occur at
2287 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002288 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002289 }
Chet Haase91d25932013-04-11 15:24:55 -07002290 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002291
2292 first = false;
2293 });
Mathias Agopian84300952012-11-21 16:02:13 -08002294 }
2295
2296
Mathias Agopian3559b072012-08-15 13:46:03 -07002297 /*
2298 * Perform our own transaction if needed
2299 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002300
2301 if (mLayersAdded) {
2302 mLayersAdded = false;
2303 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002304 mVisibleRegionsDirty = true;
2305 }
2306
2307 // some layers might have been removed, so
2308 // we need to update the regions they're exposing.
2309 if (mLayersRemoved) {
2310 mLayersRemoved = false;
2311 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002312 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002313 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002314 // this layer is not visible anymore
2315 // TODO: we could traverse the tree from front to back and
2316 // compute the actual visible region
2317 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002318 Region visibleReg;
2319 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002320 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002321 }
Robert Carr2047fae2016-11-28 14:09:09 -08002322 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002323 }
2324
2325 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002326
2327 updateCursorAsync();
2328}
2329
2330void SurfaceFlinger::updateCursorAsync()
2331{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002332 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2333 auto& displayDevice = mDisplays[displayId];
2334 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002335 continue;
2336 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002337
2338 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2339 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002340 }
2341 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002342}
2343
2344void SurfaceFlinger::commitTransaction()
2345{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002346 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002347 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002348 for (const auto& l : mLayersPendingRemoval) {
2349 recordBufferingStats(l->getName().string(),
2350 l->getOccupancyHistory(true));
2351 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002352 }
2353 mLayersPendingRemoval.clear();
2354 }
2355
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002356 // If this transaction is part of a window animation then the next frame
2357 // we composite should be considered an animation as well.
2358 mAnimCompositionPending = mAnimTransactionPending;
2359
Mathias Agopian4fec8732012-06-29 14:12:52 -07002360 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002361 mDrawingState.traverseInZOrder([](Layer* layer) {
2362 layer->commitChildList();
2363 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002364 mTransactionPending = false;
2365 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002366 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367}
2368
Chia-I Wuab0c3192017-08-01 11:29:00 -07002369void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002370 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002371{
Mathias Agopian841cde52012-03-01 15:44:37 -08002372 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002373 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002374
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002375 Region aboveOpaqueLayers;
2376 Region aboveCoveredLayers;
2377 Region dirty;
2378
Mathias Agopian87baae12012-07-31 12:38:26 -07002379 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002380
Robert Carr2047fae2016-11-28 14:09:09 -08002381 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002382 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002383 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384
Jesse Hall01e29052013-02-19 16:13:35 -08002385 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002386 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002387 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002388
Mathias Agopianab028732010-03-16 16:41:46 -07002389 /*
2390 * opaqueRegion: area of a surface that is fully opaque.
2391 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002393
2394 /*
2395 * visibleRegion: area of a surface that is visible on screen
2396 * and not fully transparent. This is essentially the layer's
2397 * footprint minus the opaque regions above it.
2398 * Areas covered by a translucent surface are considered visible.
2399 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002400 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002401
2402 /*
2403 * coveredRegion: area of a surface that is covered by all
2404 * visible regions above it (which includes the translucent areas).
2405 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002406 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002407
Jesse Halla8026d22012-09-25 13:25:04 -07002408 /*
2409 * transparentRegion: area of a surface that is hinted to be completely
2410 * transparent. This is only used to tell when the layer has no visible
2411 * non-transparent regions and can be removed from the layer list. It
2412 * does not affect the visibleRegion of this layer or any layers
2413 * beneath it. The hint may not be correct if apps don't respect the
2414 * SurfaceView restrictions (which, sadly, some don't).
2415 */
2416 Region transparentRegion;
2417
Mathias Agopianab028732010-03-16 16:41:46 -07002418
2419 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002420 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002421 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002422 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002423 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002424 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002425 if (!visibleRegion.isEmpty()) {
2426 // Remove the transparent area from the visible region
2427 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002428 if (tr.preserveRects()) {
2429 // transform the transparent region
2430 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002431 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002432 // transformation too complex, can't do the
2433 // transparent region optimization.
2434 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002435 }
Mathias Agopianab028732010-03-16 16:41:46 -07002436 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002437
Mathias Agopianab028732010-03-16 16:41:46 -07002438 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002439 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002440 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002441 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2442 // the opaque region is the layer's footprint
2443 opaqueRegion = visibleRegion;
2444 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445 }
2446 }
2447
Mathias Agopianab028732010-03-16 16:41:46 -07002448 // Clip the covered region to the visible region
2449 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2450
2451 // Update aboveCoveredLayers for next (lower) layer
2452 aboveCoveredLayers.orSelf(visibleRegion);
2453
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454 // subtract the opaque region covered by the layers above us
2455 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456
2457 // compute this layer's dirty region
2458 if (layer->contentDirty) {
2459 // we need to invalidate the whole region
2460 dirty = visibleRegion;
2461 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002462 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463 layer->contentDirty = false;
2464 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002465 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002466 * the exposed region consists of two components:
2467 * 1) what's VISIBLE now and was COVERED before
2468 * 2) what's EXPOSED now less what was EXPOSED before
2469 *
2470 * note that (1) is conservative, we start with the whole
2471 * visible region but only keep what used to be covered by
2472 * something -- which mean it may have been exposed.
2473 *
2474 * (2) handles areas that were not covered by anything but got
2475 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002476 */
Mathias Agopianab028732010-03-16 16:41:46 -07002477 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002478 const Region oldVisibleRegion = layer->visibleRegion;
2479 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002480 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2481 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482 }
2483 dirty.subtractSelf(aboveOpaqueLayers);
2484
2485 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002486 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487
Mathias Agopianab028732010-03-16 16:41:46 -07002488 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002490
Jesse Halla8026d22012-09-25 13:25:04 -07002491 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492 layer->setVisibleRegion(visibleRegion);
2493 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002494 layer->setVisibleNonTransparentRegion(
2495 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002496 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497
Mathias Agopian87baae12012-07-31 12:38:26 -07002498 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499}
2500
Chia-I Wuab0c3192017-08-01 11:29:00 -07002501void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002502 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002503 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002504 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002505 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002506 }
2507 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002508}
2509
Dan Stoza6b9454d2014-11-07 16:00:59 -08002510bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002512 ALOGV("handlePageFlip");
2513
Brian Andersond6927fb2016-07-23 23:37:30 -07002514 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515
Mathias Agopian4fec8732012-06-29 14:12:52 -07002516 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002517 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002518 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002519
2520 // Store the set of layers that need updates. This set must not change as
2521 // buffers are being latched, as this could result in a deadlock.
2522 // Example: Two producers share the same command stream and:
2523 // 1.) Layer 0 is latched
2524 // 2.) Layer 0 gets a new frame
2525 // 2.) Layer 1 gets a new frame
2526 // 3.) Layer 1 is latched.
2527 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2528 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002529 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002530 if (layer->hasQueuedFrame()) {
2531 frameQueued = true;
2532 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002533 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002534 } else {
2535 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002536 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002537 } else {
2538 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002539 }
Robert Carr2047fae2016-11-28 14:09:09 -08002540 });
2541
Dan Stoza9e56aa02015-11-02 13:00:03 -08002542 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002543 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002544 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002545 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002546 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002547 newDataLatched = true;
2548 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002549 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002550
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002551 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002552
2553 // If we will need to wake up at some time in the future to deal with a
2554 // queued frame that shouldn't be displayed during this vsync period, wake
2555 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002556 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002557 signalLayerUpdate();
2558 }
2559
2560 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002561 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562}
2563
Mathias Agopianad456f92011-01-13 17:53:01 -08002564void SurfaceFlinger::invalidateHwcGeometry()
2565{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002566 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002567}
2568
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002569
Fabien Sanglard830b8472016-11-30 16:35:58 -08002570void SurfaceFlinger::doDisplayComposition(
2571 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002572 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573{
Dan Stoza71433162014-02-04 16:22:36 -08002574 // We only need to actually compose the display if:
2575 // 1) It is being handled by hardware composer, which may need this to
2576 // keep its virtual display state machine in sync, or
2577 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002578 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002579 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002580 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002581 return;
2582 }
2583
Dan Stoza9e56aa02015-11-02 13:00:03 -08002584 ALOGV("doDisplayComposition");
2585
Mathias Agopian87baae12012-07-31 12:38:26 -07002586 Region dirtyRegion(inDirtyRegion);
2587
Mathias Agopianb8a55602009-06-26 19:06:36 -07002588 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002589 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590
Fabien Sanglard830b8472016-11-30 16:35:58 -08002591 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002592 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002593 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2594 // takes a rectangle, we must make sure to update that whole
2595 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002596 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002597 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002598 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002599 // We need to redraw the rectangle that will be updated
2600 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002601 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002602 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002603 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002604 } else {
2605 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002606 dirtyRegion.set(displayDevice->bounds());
2607 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608 }
2609 }
2610
Fabien Sanglard830b8472016-11-30 16:35:58 -08002611 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002613 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002614 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002615
2616 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002617 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618}
2619
Dan Stoza9e56aa02015-11-02 13:00:03 -08002620bool SurfaceFlinger::doComposeSurfaces(
2621 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002622{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002623 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002624
Dan Stoza9e56aa02015-11-02 13:00:03 -08002625 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002626
2627 mat4 oldColorMatrix;
2628 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2629 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2630 if (applyColorMatrix) {
2631 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2632 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2633 }
2634
Dan Stoza9e56aa02015-11-02 13:00:03 -08002635 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2636 if (hasClientComposition) {
2637 ALOGV("hasClientComposition");
2638
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002639#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002640 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002641 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002642#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002643 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002644 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002645 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002646 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002647
2648 // |mStateLock| not needed as we are on the main thread
2649 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002650 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2651 }
2652 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002653 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002654
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002655 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002656 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2657 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002658 // when using overlays, we assume a fully transparent framebuffer
2659 // NOTE: we could reduce how much we need to clear, for instance
2660 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002661 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002662 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002664 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002665 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002666 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002667
2668 // we remove the scissor part
2669 // we're left with the letterbox region
2670 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002672
2673 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002674 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002675
2676 // but limit it to the dirty region
2677 region.andSelf(dirty);
2678
Mathias Agopianb9494d52012-04-18 02:28:45 -07002679 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002680 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002681 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002682 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002683 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002684 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002685
Dan Stoza9e56aa02015-11-02 13:00:03 -08002686 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002687 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002688 // scissor on the main display. It should never be needed
2689 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002690 const Rect& bounds(displayDevice->getBounds());
2691 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002692 if (scissor != bounds) {
2693 // scissor doesn't match the screen's dimensions, so we
2694 // need to clear everything outside of it and enable
2695 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002696
Mathias Agopianf45c5102012-10-24 16:29:17 -07002697 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002698 const uint32_t height = displayDevice->getHeight();
2699 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002700 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002701 }
2702 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002703 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002704
Mathias Agopian85d751c2012-08-29 16:59:24 -07002705 /*
2706 * and then, render the layers targeted at the framebuffer
2707 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002708
Dan Stoza9e56aa02015-11-02 13:00:03 -08002709 ALOGV("Rendering client layers");
2710 const Transform& displayTransform = displayDevice->getTransform();
2711 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002712 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002713 bool firstLayer = true;
2714 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2715 const Region clip(dirty.intersect(
2716 displayTransform.transform(layer->visibleRegion)));
2717 ALOGV("Layer: %s", layer->getName().string());
2718 ALOGV(" Composition type: %s",
2719 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002720 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002721 switch (layer->getCompositionType(hwcId)) {
2722 case HWC2::Composition::Cursor:
2723 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002724 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002725 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002726 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002727 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2728 layer->isOpaque(state) && (state.alpha == 1.0f)
2729 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002730 // never clear the very first layer since we're
2731 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002732 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002733 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002734 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002735 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002736 case HWC2::Composition::Client: {
2737 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002738 break;
2739 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002741 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002742 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002743 } else {
2744 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002745 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002746 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002747 }
2748 } else {
2749 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002750 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002751 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002753 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002754 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002755 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002756 }
2757 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002758
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002759 if (applyColorMatrix) {
2760 getRenderEngine().setupColorTransform(oldColorMatrix);
2761 }
2762
Mathias Agopianf45c5102012-10-24 16:29:17 -07002763 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002764 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002765 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766}
2767
Fabien Sanglard830b8472016-11-30 16:35:58 -08002768void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2769 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002770 RenderEngine& engine(getRenderEngine());
2771 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772}
2773
Dan Stoza7d89d062015-04-30 13:29:25 -07002774status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002775 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002776 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002777 const sp<Layer>& lbc,
2778 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002779{
Dan Stoza7d89d062015-04-30 13:29:25 -07002780 // add this layer to the current state list
2781 {
2782 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002783 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002784 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2785 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002786 return NO_MEMORY;
2787 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002788 if (parent == nullptr) {
2789 mCurrentState.layersSortedByZ.add(lbc);
2790 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002791 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2792 ALOGE("addClientLayer called with a removed parent");
2793 return NAME_NOT_FOUND;
2794 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002795 parent->addChild(lbc);
2796 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002797
Dan Stoza7d89d062015-04-30 13:29:25 -07002798 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002799 mLayersAdded = true;
2800 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002801 }
2802
Mathias Agopian96f08192010-06-02 23:28:45 -07002803 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002804 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002805
Dan Stoza7d89d062015-04-30 13:29:25 -07002806 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002807}
2808
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002809status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002810 Mutex::Autolock _l(mStateLock);
2811
Robert Carr1f0a16a2016-10-24 16:27:39 -07002812 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002813 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002814 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002815 if (topLevelOnly) {
2816 return NO_ERROR;
2817 }
2818
Chia-I Wu98f1c102017-05-30 14:54:08 -07002819 sp<Layer> ancestor = p;
2820 while (ancestor->getParent() != nullptr) {
2821 ancestor = ancestor->getParent();
2822 }
2823 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2824 ALOGE("removeLayer called with a layer whose parent has been removed");
2825 return NAME_NOT_FOUND;
2826 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002827
2828 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002829 } else {
2830 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002831 }
2832
Robert Carr136e2f62017-02-08 17:54:29 -08002833 // As a matter of normal operation, the LayerCleaner will produce a second
2834 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2835 // so we will succeed in promoting it, but it's already been removed
2836 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2837 // otherwise something has gone wrong and we are leaking the layer.
2838 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002839 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2840 layer->getName().string(),
2841 (p != nullptr) ? p->getName().string() : "no-parent");
2842 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002843 } else if (index < 0) {
2844 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002845 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002846
2847 mLayersPendingRemoval.add(layer);
2848 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002849 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002850 setTransactionFlags(eTransactionNeeded);
2851 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852}
2853
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002854uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002855 return android_atomic_release_load(&mTransactionFlags);
2856}
2857
Mathias Agopian3f844832013-08-07 21:24:32 -07002858uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2860}
2861
Mathias Agopian3f844832013-08-07 21:24:32 -07002862uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2864 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002865 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 }
2867 return old;
2868}
2869
Mathias Agopian8b33f032012-07-24 20:43:54 -07002870void SurfaceFlinger::setTransactionState(
2871 const Vector<ComposerState>& state,
2872 const Vector<DisplayState>& displays,
2873 uint32_t flags)
2874{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002875 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002876 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002877 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002878
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002879 if (flags & eAnimation) {
2880 // For window updates that are part of an animation we must wait for
2881 // previous animation "frames" to be handled.
2882 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002883 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002884 if (CC_UNLIKELY(err != NO_ERROR)) {
2885 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002886 // caller after a few seconds.
2887 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2888 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002889 mAnimTransactionPending = false;
2890 break;
2891 }
2892 }
2893 }
2894
Mathias Agopiane57f2922012-08-09 16:29:12 -07002895 size_t count = displays.size();
2896 for (size_t i=0 ; i<count ; i++) {
2897 const DisplayState& s(displays[i]);
2898 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002899 }
2900
Mathias Agopiane57f2922012-08-09 16:29:12 -07002901 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002902 for (size_t i=0 ; i<count ; i++) {
2903 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002904 // Here we need to check that the interface we're given is indeed
2905 // one of our own. A malicious client could give us a NULL
2906 // IInterface, or one of its own or even one of our own but a
2907 // different type. All these situations would cause us to crash.
2908 //
2909 // NOTE: it would be better to use RTTI as we could directly check
2910 // that we have a Client*. however, RTTI is disabled in Android.
2911 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002912 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002913 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002914 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002915 sp<Client> client( static_cast<Client *>(s.client.get()) );
2916 transactionFlags |= setClientStateLocked(client, s.state);
2917 }
2918 }
2919 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002920 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002921
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002922 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2923 // anyway. This can be used as a flush mechanism for previous async transactions.
2924 // Empty animation transaction can be used to simulate back-pressure, so also force a
2925 // transaction for empty animation transactions.
2926 if (transactionFlags == 0 &&
2927 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002928 transactionFlags = eTransactionNeeded;
2929 }
2930
Mathias Agopian386aa982011-11-07 21:58:03 -08002931 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002932 if (mInterceptor.isEnabled()) {
2933 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2934 }
Irvel468051e2016-06-13 16:44:44 -07002935
Mathias Agopian386aa982011-11-07 21:58:03 -08002936 // this triggers the transaction
2937 setTransactionFlags(transactionFlags);
2938
2939 // if this is a synchronous transaction, wait for it to take effect
2940 // before returning.
2941 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002942 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002943 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002944 if (flags & eAnimation) {
2945 mAnimTransactionPending = true;
2946 }
2947 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002948 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2949 if (CC_UNLIKELY(err != NO_ERROR)) {
2950 // just in case something goes wrong in SF, return to the
2951 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002952 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2953 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002954 break;
2955 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002956 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957 }
2958}
2959
Mathias Agopiane57f2922012-08-09 16:29:12 -07002960uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2961{
Jesse Hall9a143922012-10-04 16:29:19 -07002962 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2963 if (dpyIdx < 0)
2964 return 0;
2965
Mathias Agopiane57f2922012-08-09 16:29:12 -07002966 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002967 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002968 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002969 const uint32_t what = s.what;
2970 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002971 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002972 disp.surface = s.surface;
2973 flags |= eDisplayTransactionNeeded;
2974 }
2975 }
2976 if (what & DisplayState::eLayerStackChanged) {
2977 if (disp.layerStack != s.layerStack) {
2978 disp.layerStack = s.layerStack;
2979 flags |= eDisplayTransactionNeeded;
2980 }
2981 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002982 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002983 if (disp.orientation != s.orientation) {
2984 disp.orientation = s.orientation;
2985 flags |= eDisplayTransactionNeeded;
2986 }
2987 if (disp.frame != s.frame) {
2988 disp.frame = s.frame;
2989 flags |= eDisplayTransactionNeeded;
2990 }
2991 if (disp.viewport != s.viewport) {
2992 disp.viewport = s.viewport;
2993 flags |= eDisplayTransactionNeeded;
2994 }
2995 }
Michael Lentine47e45402014-07-18 15:34:25 -07002996 if (what & DisplayState::eDisplaySizeChanged) {
2997 if (disp.width != s.width) {
2998 disp.width = s.width;
2999 flags |= eDisplayTransactionNeeded;
3000 }
3001 if (disp.height != s.height) {
3002 disp.height = s.height;
3003 flags |= eDisplayTransactionNeeded;
3004 }
3005 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003006 }
3007 return flags;
3008}
3009
3010uint32_t SurfaceFlinger::setClientStateLocked(
3011 const sp<Client>& client,
3012 const layer_state_t& s)
3013{
3014 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003015 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003016 if (layer != 0) {
3017 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003018 bool geometryAppliesWithResize =
3019 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003020 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003021 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003022 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003023 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003024 }
3025 if (what & layer_state_t::eLayerChanged) {
3026 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003027 const auto& p = layer->getParent();
3028 if (p == nullptr) {
3029 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3030 if (layer->setLayer(s.z) && idx >= 0) {
3031 mCurrentState.layersSortedByZ.removeAt(idx);
3032 mCurrentState.layersSortedByZ.add(layer);
3033 // we need traversal (state changed)
3034 // AND transaction (list changed)
3035 flags |= eTransactionNeeded|eTraversalNeeded;
3036 }
3037 } else {
3038 if (p->setChildLayer(layer, s.z)) {
3039 flags |= eTransactionNeeded|eTraversalNeeded;
3040 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003041 }
3042 }
Robert Carrdb66e622017-04-10 16:55:57 -07003043 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003044 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003045 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003046 mCurrentState.layersSortedByZ.removeAt(idx);
3047 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003048 flags |= eTransactionNeeded|eTraversalNeeded;
3049 }
3050 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003051 if (what & layer_state_t::eSizeChanged) {
3052 if (layer->setSize(s.w, s.h)) {
3053 flags |= eTraversalNeeded;
3054 }
3055 }
3056 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003057 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003058 flags |= eTraversalNeeded;
3059 }
3060 if (what & layer_state_t::eMatrixChanged) {
3061 if (layer->setMatrix(s.matrix))
3062 flags |= eTraversalNeeded;
3063 }
3064 if (what & layer_state_t::eTransparentRegionChanged) {
3065 if (layer->setTransparentRegionHint(s.transparentRegion))
3066 flags |= eTraversalNeeded;
3067 }
Dan Stoza23116082015-06-18 14:58:39 -07003068 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003069 if (layer->setFlags(s.flags, s.mask))
3070 flags |= eTraversalNeeded;
3071 }
3072 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003073 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003074 flags |= eTraversalNeeded;
3075 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003076 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003077 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003078 flags |= eTraversalNeeded;
3079 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003080 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003081 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003082 // We only allow setting layer stacks for top level layers,
3083 // everything else inherits layer stack from its parent.
3084 if (layer->hasParent()) {
3085 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3086 layer->getName().string());
3087 } else if (idx < 0) {
3088 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3089 "that also does not appear in the top level layer list. Something"
3090 " has gone wrong.", layer->getName().string());
3091 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003092 mCurrentState.layersSortedByZ.removeAt(idx);
3093 mCurrentState.layersSortedByZ.add(layer);
3094 // we need traversal (state changed)
3095 // AND transaction (list changed)
3096 flags |= eTransactionNeeded|eTraversalNeeded;
3097 }
3098 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003099 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003100 if (s.barrierHandle != nullptr) {
3101 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3102 } else if (s.barrierGbp != nullptr) {
3103 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3104 if (authenticateSurfaceTextureLocked(gbp)) {
3105 const auto& otherLayer =
3106 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3107 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3108 } else {
3109 ALOGE("Attempt to defer transaction to to an"
3110 " unrecognized GraphicBufferProducer");
3111 }
3112 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003113 // We don't trigger a traversal here because if no other state is
3114 // changed, we don't want this to cause any more work
3115 }
Robert Carr1db73f62016-12-21 12:58:51 -08003116 if (what & layer_state_t::eReparentChildren) {
3117 if (layer->reparentChildren(s.reparentHandle)) {
3118 flags |= eTransactionNeeded|eTraversalNeeded;
3119 }
3120 }
Robert Carr9524cb32017-02-13 11:32:32 -08003121 if (what & layer_state_t::eDetachChildren) {
3122 layer->detachChildren();
3123 }
Robert Carrc3574f72016-03-24 12:19:32 -07003124 if (what & layer_state_t::eOverrideScalingModeChanged) {
3125 layer->setOverrideScalingMode(s.overrideScalingMode);
3126 // We don't trigger a traversal here because if no other state is
3127 // changed, we don't want this to cause any more work
3128 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003129 }
3130 return flags;
3131}
3132
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003133status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003134 const String8& name,
3135 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003136 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003137 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3138 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003140 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003141 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003142 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003143 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003144 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003145
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003146 status_t result = NO_ERROR;
3147
3148 sp<Layer> layer;
3149
Cody Northropbc755282017-03-31 12:00:08 -06003150 String8 uniqueName = getUniqueLayerName(name);
3151
Mathias Agopian3165cc22012-08-08 19:42:09 -07003152 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3153 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003154 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003155 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003156 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003158 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003159 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003160 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003161 handle, gbp, &layer);
3162 break;
3163 default:
3164 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165 break;
3166 }
3167
Dan Stoza7d89d062015-04-30 13:29:25 -07003168 if (result != NO_ERROR) {
3169 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003171
Chia-I Wuab0c3192017-08-01 11:29:00 -07003172 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3173 // TODO b/64227542
3174 if (windowType == 441731) {
3175 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3176 layer->setPrimaryDisplayOnly();
3177 }
3178
Albert Chaulk479c60c2017-01-27 14:21:34 -05003179 layer->setInfo(windowType, ownerUid);
3180
Robert Carr1f0a16a2016-10-24 16:27:39 -07003181 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003182 if (result != NO_ERROR) {
3183 return result;
3184 }
Irvelffc9efc2016-07-27 15:16:37 -07003185 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003186
3187 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003188 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003189}
3190
Cody Northropbc755282017-03-31 12:00:08 -06003191String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3192{
3193 bool matchFound = true;
3194 uint32_t dupeCounter = 0;
3195
3196 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3197 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3198
3199 // Loop over layers until we're sure there is no matching name
3200 while (matchFound) {
3201 matchFound = false;
3202 mDrawingState.traverseInZOrder([&](Layer* layer) {
3203 if (layer->getName() == uniqueName) {
3204 matchFound = true;
3205 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3206 }
3207 });
3208 }
3209
3210 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3211
3212 return uniqueName;
3213}
3214
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003215status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3216 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3217 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003218{
3219 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003220 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221 case PIXEL_FORMAT_TRANSPARENT:
3222 case PIXEL_FORMAT_TRANSLUCENT:
3223 format = PIXEL_FORMAT_RGBA_8888;
3224 break;
3225 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003226 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227 break;
3228 }
3229
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003230 *outLayer = new Layer(this, client, name, w, h, flags);
3231 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3232 if (err == NO_ERROR) {
3233 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003234 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003236
3237 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3238 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239}
3240
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003241status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3242 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3243 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003244{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003245 *outLayer = new LayerDim(this, client, name, w, h, flags);
3246 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003247 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003248 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003249}
3250
Mathias Agopianac9fa422013-02-11 16:40:36 -08003251status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252{
Robert Carr9524cb32017-02-13 11:32:32 -08003253 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003254 status_t err = NO_ERROR;
3255 sp<Layer> l(client->getLayerUser(handle));
3256 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003257 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003258 err = removeLayer(l);
3259 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3260 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003261 }
3262 return err;
3263}
3264
Mathias Agopian13127d82013-03-05 17:47:11 -08003265status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003266{
Mathias Agopian67106042013-03-14 19:18:13 -07003267 // called by ~LayerCleaner() when all references to the IBinder (handle)
3268 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003269 sp<Layer> l = layer.promote();
3270 if (l == nullptr) {
3271 // The layer has already been removed, carry on
3272 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003273 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003274 // If we have a parent, then we can continue to live as long as it does.
3275 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003276}
3277
Mathias Agopianb60314a2012-04-10 22:09:54 -07003278// ---------------------------------------------------------------------------
3279
Andy McFadden13a082e2012-08-24 10:16:42 -07003280void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003281 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003282 Vector<ComposerState> state;
3283 Vector<DisplayState> displays;
3284 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003285 d.what = DisplayState::eDisplayProjectionChanged |
3286 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003287 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003288 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003289 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003290 d.frame.makeInvalid();
3291 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003292 d.width = 0;
3293 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003294 displays.add(d);
3295 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003296 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3297 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003298
Dan Stoza9e56aa02015-11-02 13:00:03 -08003299 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3300 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003301 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003302
Brian Andersond0010582017-03-07 13:20:31 -08003303 // Use phase of 0 since phase is not known.
3304 // Use latency of 0, which will snap to the ideal latency.
3305 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003306}
3307
3308void SurfaceFlinger::initializeDisplays() {
3309 class MessageScreenInitialized : public MessageBase {
3310 SurfaceFlinger* flinger;
3311 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003312 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003313 virtual bool handler() {
3314 flinger->onInitializeDisplays();
3315 return true;
3316 }
3317 };
3318 sp<MessageBase> msg = new MessageScreenInitialized(this);
3319 postMessageAsync(msg); // we may be called from main thread, use async message
3320}
3321
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003322void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003323 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003324 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3325 this);
3326 int32_t type = hw->getDisplayType();
3327 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003328
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003329 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003330 return;
3331 }
3332
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003333 hw->setPowerMode(mode);
3334 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3335 ALOGW("Trying to set power mode for virtual display");
3336 return;
3337 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003338
Irvelffc9efc2016-07-27 15:16:37 -07003339 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003340 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003341 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3342 if (idx < 0) {
3343 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3344 return;
3345 }
3346 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3347 }
3348
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003349 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003350 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003351 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003352 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3353 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003354 // FIXME: eventthread only knows about the main display right now
3355 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003356 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003357 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003358
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003359 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003360 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003361 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003362
3363 struct sched_param param = {0};
3364 param.sched_priority = 1;
3365 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3366 ALOGW("Couldn't set SCHED_FIFO on display on");
3367 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003368 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003369 // Turn off the display
3370 struct sched_param param = {0};
3371 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3372 ALOGW("Couldn't set SCHED_OTHER on display off");
3373 }
3374
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003375 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003376 disableHardwareVsync(true); // also cancels any in-progress resync
3377
Mathias Agopiancde87a32012-09-13 14:09:01 -07003378 // FIXME: eventthread only knows about the main display right now
3379 mEventThread->onScreenReleased();
3380 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003381
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003382 getHwComposer().setPowerMode(type, mode);
3383 mVisibleRegionsDirty = true;
3384 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003385 } else if (mode == HWC_POWER_MODE_DOZE ||
3386 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003387 // Update display while dozing
3388 getHwComposer().setPowerMode(type, mode);
3389 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3390 // FIXME: eventthread only knows about the main display right now
3391 mEventThread->onScreenAcquired();
3392 resyncToHardwareVsync(true);
3393 }
3394 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3395 // Leave display going to doze
3396 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3397 disableHardwareVsync(true); // also cancels any in-progress resync
3398 // FIXME: eventthread only knows about the main display right now
3399 mEventThread->onScreenReleased();
3400 }
3401 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003402 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003403 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003404 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003405 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003406}
3407
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003408void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3409 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003410 SurfaceFlinger& mFlinger;
3411 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003412 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003413 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003414 MessageSetPowerMode(SurfaceFlinger& flinger,
3415 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3416 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003417 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003418 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003419 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003420 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003421 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003422 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003423 ALOGW("Attempt to set power mode = %d for virtual display",
3424 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003425 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003426 mFlinger.setPowerModeInternal(
3427 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003428 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003429 return true;
3430 }
3431 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003432 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003433 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003434}
3435
3436// ---------------------------------------------------------------------------
3437
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003438status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3439{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003440 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003441
Mathias Agopianbd115332013-04-18 16:41:04 -07003442 IPCThreadState* ipc = IPCThreadState::self();
3443 const int pid = ipc->getCallingPid();
3444 const int uid = ipc->getCallingUid();
3445 if ((uid != AID_SHELL) &&
3446 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003447 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003448 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003449 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003450 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003451 // (this would indicate SF is stuck, but we want to be able to
3452 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003453 status_t err = mStateLock.timedLock(s2ns(1));
3454 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003455 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003456 result.appendFormat(
3457 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3458 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003459 }
3460
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003461 bool dumpAll = true;
3462 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003463 size_t numArgs = args.size();
3464 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003465 if ((index < numArgs) &&
3466 (args[index] == String16("--list"))) {
3467 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003468 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003469 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003470 }
3471
3472 if ((index < numArgs) &&
3473 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003474 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003475 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003476 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003477 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003478
3479 if ((index < numArgs) &&
3480 (args[index] == String16("--latency-clear"))) {
3481 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003482 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003483 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003484 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003485
3486 if ((index < numArgs) &&
3487 (args[index] == String16("--dispsync"))) {
3488 index++;
3489 mPrimaryDispSync.dump(result);
3490 dumpAll = false;
3491 }
Dan Stozab90cf072015-03-05 11:05:59 -08003492
3493 if ((index < numArgs) &&
3494 (args[index] == String16("--static-screen"))) {
3495 index++;
3496 dumpStaticScreenStats(result);
3497 dumpAll = false;
3498 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003499
3500 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003501 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003502 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003503 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003504 dumpAll = false;
3505 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003506
3507 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3508 index++;
3509 dumpWideColorInfo(result);
3510 dumpAll = false;
3511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003513
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003514 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003515 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003516 }
3517
Mathias Agopian9795c422009-08-26 16:36:26 -07003518 if (locked) {
3519 mStateLock.unlock();
3520 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 }
3522 write(fd, result.string(), result.size());
3523 return NO_ERROR;
3524}
3525
Dan Stozac7014012014-02-14 15:03:43 -08003526void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3527 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003528{
Robert Carr2047fae2016-11-28 14:09:09 -08003529 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003530 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003531 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003532}
3533
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003534void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003535 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003536{
3537 String8 name;
3538 if (index < args.size()) {
3539 name = String8(args[index]);
3540 index++;
3541 }
3542
Dan Stoza9e56aa02015-11-02 13:00:03 -08003543 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3544 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003545 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003546
3547 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003548 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003549 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003550 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003551 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003552 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003553 }
Robert Carr2047fae2016-11-28 14:09:09 -08003554 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003555 }
3556}
3557
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003558void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003559 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003560{
3561 String8 name;
3562 if (index < args.size()) {
3563 name = String8(args[index]);
3564 index++;
3565 }
3566
Robert Carr2047fae2016-11-28 14:09:09 -08003567 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003568 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003569 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003570 }
Robert Carr2047fae2016-11-28 14:09:09 -08003571 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003572
Svetoslavd85084b2014-03-20 10:28:31 -07003573 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003574}
3575
Jamie Gennis6547ff42013-07-16 20:12:42 -07003576// This should only be called from the main thread. Otherwise it would need
3577// the lock and should use mCurrentState rather than mDrawingState.
3578void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003579 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003580 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003581 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003582
3583 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3584}
3585
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003586void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003587{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003588 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003589 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3590
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003591 if (isLayerTripleBufferingDisabled())
3592 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003593
3594 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003595 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003596 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003597 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003598 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3599 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003600 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003601}
3602
Dan Stozab90cf072015-03-05 11:05:59 -08003603void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3604{
3605 result.appendFormat("Static screen stats:\n");
3606 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3607 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3608 float percent = 100.0f *
3609 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3610 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3611 b + 1, bucketTimeSec, percent);
3612 }
3613 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3614 float percent = 100.0f *
3615 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3616 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3617 NUM_BUCKETS - 1, bucketTimeSec, percent);
3618}
3619
Dan Stozae77c7662016-05-13 11:37:28 -07003620void SurfaceFlinger::recordBufferingStats(const char* layerName,
3621 std::vector<OccupancyTracker::Segment>&& history) {
3622 Mutex::Autolock lock(mBufferingStatsMutex);
3623 auto& stats = mBufferingStats[layerName];
3624 for (const auto& segment : history) {
3625 if (!segment.usedThirdBuffer) {
3626 stats.twoBufferTime += segment.totalTime;
3627 }
3628 if (segment.occupancyAverage < 1.0f) {
3629 stats.doubleBufferedTime += segment.totalTime;
3630 } else if (segment.occupancyAverage < 2.0f) {
3631 stats.tripleBufferedTime += segment.totalTime;
3632 }
3633 ++stats.numSegments;
3634 stats.totalTime += segment.totalTime;
3635 }
3636}
3637
Brian Andersond6927fb2016-07-23 23:37:30 -07003638void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3639 result.appendFormat("Layer frame timestamps:\n");
3640
3641 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3642 const size_t count = currentLayers.size();
3643 for (size_t i=0 ; i<count ; i++) {
3644 currentLayers[i]->dumpFrameEvents(result);
3645 }
3646}
3647
Dan Stozae77c7662016-05-13 11:37:28 -07003648void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3649 result.append("Buffering stats:\n");
3650 result.append(" [Layer name] <Active time> <Two buffer> "
3651 "<Double buffered> <Triple buffered>\n");
3652 Mutex::Autolock lock(mBufferingStatsMutex);
3653 typedef std::tuple<std::string, float, float, float> BufferTuple;
3654 std::map<float, BufferTuple, std::greater<float>> sorted;
3655 for (const auto& statsPair : mBufferingStats) {
3656 const char* name = statsPair.first.c_str();
3657 const BufferingStats& stats = statsPair.second;
3658 if (stats.numSegments == 0) {
3659 continue;
3660 }
3661 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3662 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3663 stats.totalTime;
3664 float doubleBufferRatio = static_cast<float>(
3665 stats.doubleBufferedTime) / stats.totalTime;
3666 float tripleBufferRatio = static_cast<float>(
3667 stats.tripleBufferedTime) / stats.totalTime;
3668 sorted.insert({activeTime, {name, twoBufferRatio,
3669 doubleBufferRatio, tripleBufferRatio}});
3670 }
3671 for (const auto& sortedPair : sorted) {
3672 float activeTime = sortedPair.first;
3673 const BufferTuple& values = sortedPair.second;
3674 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3675 std::get<0>(values).c_str(), activeTime,
3676 std::get<1>(values), std::get<2>(values),
3677 std::get<3>(values));
3678 }
3679 result.append("\n");
3680}
3681
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003682void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3683 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3684
3685 // TODO: print out if wide-color mode is active or not
3686
3687 for (size_t d = 0; d < mDisplays.size(); d++) {
3688 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3689 int32_t hwcId = displayDevice->getHwcDisplayId();
3690 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3691 continue;
3692 }
3693
3694 result.appendFormat("Display %d color modes:\n", hwcId);
3695 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3696 for (auto&& mode : modes) {
3697 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3698 }
3699
3700 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3701 result.appendFormat(" Current color mode: %s (%d)\n",
3702 decodeColorMode(currentMode).c_str(), currentMode);
3703 }
3704 result.append("\n");
3705}
3706
Mathias Agopian74d211a2013-04-22 16:55:35 +02003707void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3708 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003709{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003710 bool colorize = false;
3711 if (index < args.size()
3712 && (args[index] == String16("--color"))) {
3713 colorize = true;
3714 index++;
3715 }
3716
3717 Colorizer colorizer(colorize);
3718
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003719 // figure out if we're stuck somewhere
3720 const nsecs_t now = systemTime();
3721 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3722 const nsecs_t inTransaction(mDebugInTransaction);
3723 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3724 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3725
3726 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003727 * Dump library configuration.
3728 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003729
3730 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003731 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003732 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003733 appendSfConfigString(result);
3734 appendUiConfigString(result);
3735 appendGuiConfigString(result);
3736 result.append("\n");
3737
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003738 result.append("\nWide-Color information:\n");
3739 dumpWideColorInfo(result);
3740
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003741 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003742 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003743 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003744 result.append(SyncFeatures::getInstance().toString());
3745 result.append("\n");
3746
Dan Stoza9e56aa02015-11-02 13:00:03 -08003747 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3748
Andy McFadden41d67d72014-04-25 16:58:34 -07003749 colorizer.bold(result);
3750 result.append("DispSync configuration: ");
3751 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003752 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003753 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003754 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003755 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003756 result.append("\n");
3757
Dan Stozab90cf072015-03-05 11:05:59 -08003758 // Dump static screen stats
3759 result.append("\n");
3760 dumpStaticScreenStats(result);
3761 result.append("\n");
3762
Dan Stozae77c7662016-05-13 11:37:28 -07003763 dumpBufferingStats(result);
3764
Andy McFadden4803b742012-09-24 19:07:20 -07003765 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003766 * Dump the visible layer list
3767 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003768 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003769 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003770 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003771 mCurrentState.traverseInZOrder([&](Layer* layer) {
Kalle Raitaa099a242017-01-11 11:17:29 -08003772 result.append(to_string(layer->getLayerDebugInfo()).c_str());
Robert Carr2047fae2016-11-28 14:09:09 -08003773 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003774
3775 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003776 * Dump Display state
3777 */
3778
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003779 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003780 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003781 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003782 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3783 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003784 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003785 }
3786
3787 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003788 * Dump SurfaceFlinger global state
3789 */
3790
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003791 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003792 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003793 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003794
Mathias Agopian888c8222012-08-04 21:10:38 -07003795 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003796 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003797
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003798 colorizer.bold(result);
3799 result.appendFormat("EGL implementation : %s\n",
3800 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3801 colorizer.reset(result);
3802 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003803 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003804
Mathias Agopian875d8e12013-06-07 15:35:48 -07003805 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003806
Mathias Agopian42977342012-08-05 00:40:46 -07003807 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003808 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3809 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003810 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003811 " last eglSwapBuffers() time: %f us\n"
3812 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003813 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003814 " refresh-rate : %f fps\n"
3815 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003816 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003817 " gpu_to_cpu_unsupported : %d\n"
3818 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003819 mLastSwapBufferTime/1000.0,
3820 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003821 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003822 1e9 / activeConfig->getVsyncPeriod(),
3823 activeConfig->getDpiX(),
3824 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003825 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003826
Mathias Agopian74d211a2013-04-22 16:55:35 +02003827 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003828 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003829
Mathias Agopian74d211a2013-04-22 16:55:35 +02003830 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003831 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003832
3833 /*
3834 * VSYNC state
3835 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003836 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003837 result.append("\n");
3838
3839 /*
3840 * HWC layer minidump
3841 */
3842 for (size_t d = 0; d < mDisplays.size(); d++) {
3843 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3844 int32_t hwcId = displayDevice->getHwcDisplayId();
3845 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3846 continue;
3847 }
3848
3849 result.appendFormat("Display %d HWC layers:\n", hwcId);
3850 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003851 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003852 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003853 });
Dan Stozae22aec72016-08-01 13:20:59 -07003854 result.append("\n");
3855 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003856
3857 /*
3858 * Dump HWComposer state
3859 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003860 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003861 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003862 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003863 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003864 result.appendFormat(" h/w composer %s\n",
3865 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003866 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003867
3868 /*
3869 * Dump gralloc state
3870 */
3871 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3872 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003873
3874 /*
3875 * Dump VrFlinger state if in use.
3876 */
3877 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3878 result.append("VrFlinger state:\n");
3879 result.append(mVrFlinger->Dump().c_str());
3880 result.append("\n");
3881 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003882}
3883
Mathias Agopian13127d82013-03-05 17:47:11 -08003884const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003885SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003886 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003887 wp<IBinder> dpy;
3888 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3889 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3890 dpy = mDisplays.keyAt(i);
3891 break;
3892 }
3893 }
3894 if (dpy == NULL) {
3895 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3896 // Just use the primary display so we have something to return
3897 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3898 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003899 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003900}
3901
Keun young Park63f165f2012-08-31 10:53:36 -07003902bool SurfaceFlinger::startDdmConnection()
3903{
3904 void* libddmconnection_dso =
3905 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3906 if (!libddmconnection_dso) {
3907 return false;
3908 }
3909 void (*DdmConnection_start)(const char* name);
3910 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003911 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003912 if (!DdmConnection_start) {
3913 dlclose(libddmconnection_dso);
3914 return false;
3915 }
3916 (*DdmConnection_start)(getServiceName());
3917 return true;
3918}
3919
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003920status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003921 switch (code) {
3922 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003923 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003924 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003925 case CLEAR_ANIMATION_FRAME_STATS:
3926 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003927 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003928 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003929 {
3930 // codes that require permission check
3931 IPCThreadState* ipc = IPCThreadState::self();
3932 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003933 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003934 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003935 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003936 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003937 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003938 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003939 break;
3940 }
Robert Carr1db73f62016-12-21 12:58:51 -08003941 /*
3942 * Calling setTransactionState is safe, because you need to have been
3943 * granted a reference to Client* and Handle* to do anything with it.
3944 *
3945 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3946 */
3947 case SET_TRANSACTION_STATE:
3948 case CREATE_SCOPED_CONNECTION:
3949 {
3950 return OK;
3951 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003952 case CAPTURE_SCREEN:
3953 {
3954 // codes that require permission check
3955 IPCThreadState* ipc = IPCThreadState::self();
3956 const int pid = ipc->getCallingPid();
3957 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003958 if ((uid != AID_GRAPHICS) &&
3959 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003960 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003961 return PERMISSION_DENIED;
3962 }
3963 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003964 }
3965 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003966 return OK;
3967}
3968
3969status_t SurfaceFlinger::onTransact(
3970 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3971{
3972 status_t credentialCheck = CheckTransactCodeCredentials(code);
3973 if (credentialCheck != OK) {
3974 return credentialCheck;
3975 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003976
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003977 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3978 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003979 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003980 IPCThreadState* ipc = IPCThreadState::self();
3981 const int uid = ipc->getCallingUid();
3982 if (CC_UNLIKELY(uid != AID_SYSTEM
3983 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003984 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003985 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003986 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003987 return PERMISSION_DENIED;
3988 }
3989 int n;
3990 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003991 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003992 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003993 return NO_ERROR;
3994 case 1002: // SHOW_UPDATES
3995 n = data.readInt32();
3996 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003997 invalidateHwcGeometry();
3998 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003999 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004000 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004001 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004002 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004003 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004004 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07004005 setTransactionFlags(
4006 eTransactionNeeded|
4007 eDisplayTransactionNeeded|
4008 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004009 return NO_ERROR;
4010 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004011 case 1006:{ // send empty update
4012 signalRefresh();
4013 return NO_ERROR;
4014 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004015 case 1008: // toggle use of hw composer
4016 n = data.readInt32();
4017 mDebugDisableHWC = n ? 1 : 0;
4018 invalidateHwcGeometry();
4019 repaintEverything();
4020 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004021 case 1009: // toggle use of transform hint
4022 n = data.readInt32();
4023 mDebugDisableTransformHint = n ? 1 : 0;
4024 invalidateHwcGeometry();
4025 repaintEverything();
4026 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004027 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004028 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004029 reply->writeInt32(0);
4030 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004031 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004032 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004033 return NO_ERROR;
4034 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004035 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004036 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004037 return NO_ERROR;
4038 }
4039 case 1014: {
4040 // daltonize
4041 n = data.readInt32();
4042 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004043 case 1:
4044 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4045 break;
4046 case 2:
4047 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4048 break;
4049 case 3:
4050 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4051 break;
4052 default:
4053 mDaltonizer.setType(ColorBlindnessType::None);
4054 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004055 }
4056 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004057 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004058 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004059 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004060 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004061 invalidateHwcGeometry();
4062 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004063 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004064 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004065 case 1015: {
4066 // apply a color matrix
4067 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004068 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004069 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004070 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004071 for (size_t j = 0; j < 4; j++) {
4072 mColorMatrix[i][j] = data.readFloat();
4073 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004074 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004075 } else {
4076 mColorMatrix = mat4();
4077 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004078
4079 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4080 // the division by w in the fragment shader
4081 float4 lastRow(transpose(mColorMatrix)[3]);
4082 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4083 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4084 }
4085
Alan Viverette9c5a3332013-09-12 20:04:35 -07004086 invalidateHwcGeometry();
4087 repaintEverything();
4088 return NO_ERROR;
4089 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004090 // This is an experimental interface
4091 // Needs to be shifted to proper binder interface when we productize
4092 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004093 n = data.readInt32();
4094 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004095 return NO_ERROR;
4096 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004097 case 1017: {
4098 n = data.readInt32();
4099 mForceFullDamage = static_cast<bool>(n);
4100 return NO_ERROR;
4101 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004102 case 1018: { // Modify Choreographer's phase offset
4103 n = data.readInt32();
4104 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4105 return NO_ERROR;
4106 }
4107 case 1019: { // Modify SurfaceFlinger's phase offset
4108 n = data.readInt32();
4109 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4110 return NO_ERROR;
4111 }
Irvel468051e2016-06-13 16:44:44 -07004112 case 1020: { // Layer updates interceptor
4113 n = data.readInt32();
4114 if (n) {
4115 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004116 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004117 }
4118 else{
4119 ALOGV("Interceptor disabled");
4120 mInterceptor.disable();
4121 }
4122 return NO_ERROR;
4123 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004124 case 1021: { // Disable HWC virtual displays
4125 n = data.readInt32();
4126 mUseHwcVirtualDisplays = !n;
4127 return NO_ERROR;
4128 }
Romain Guy0147a172017-06-01 13:53:56 -07004129 case 1022: { // Set saturation boost
4130 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4131
4132 invalidateHwcGeometry();
4133 repaintEverything();
4134 return NO_ERROR;
4135 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136 }
4137 }
4138 return err;
4139}
4140
Mathias Agopian53331da2011-08-22 21:44:41 -07004141void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004142 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004143 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004144}
4145
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004146// Checks that the requested width and height are valid and updates them to the display dimensions
4147// if they are set to 0
4148static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4149 Transform::orientation_flags rotation,
4150 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4151 // get screen geometry
4152 uint32_t displayWidth = displayDevice->getWidth();
4153 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004154
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004155 if (rotation & Transform::ROT_90) {
4156 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004157 }
4158
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004159 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4160 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4161 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4162 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004163 }
4164
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004165 if (*requestedWidth == 0) {
4166 *requestedWidth = displayWidth;
4167 }
4168 if (*requestedHeight == 0) {
4169 *requestedHeight = displayHeight;
4170 }
4171
4172 return NO_ERROR;
4173}
4174
4175// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4176class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004177public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004178 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4179 ~WindowDisconnector() {
4180 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004181 }
4182
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004183private:
4184 ANativeWindow* mWindow;
4185 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004186};
4187
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004188static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4189 uint32_t requestedHeight, bool hasWideColorDisplay,
4190 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4191 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4192 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4193
4194 int err = 0;
4195 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4196 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4197 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4198 err |= native_window_set_usage(window, usage);
4199
4200 if (hasWideColorDisplay) {
4201 err |= native_window_set_buffers_data_space(window,
4202 renderEngineUsesWideColor
4203 ? HAL_DATASPACE_DISPLAY_P3
4204 : HAL_DATASPACE_V0_SRGB);
4205 }
4206
4207 if (err != NO_ERROR) {
4208 return BAD_VALUE;
4209 }
4210
4211 /* TODO: Once we have the sync framework everywhere this can use
4212 * server-side waits on the fence that dequeueBuffer returns.
4213 */
4214 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4215 if (err != NO_ERROR) {
4216 return err;
4217 }
4218
4219 return NO_ERROR;
4220}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004221
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004222status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4223 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004224 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004225 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004226 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004227 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004228
4229 if (CC_UNLIKELY(display == 0))
4230 return BAD_VALUE;
4231
4232 if (CC_UNLIKELY(producer == 0))
4233 return BAD_VALUE;
4234
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004235 // if we have secure windows on this display, never allow the screen capture
4236 // unless the producer interface is local (i.e.: we can take a screenshot for
4237 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004238 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004239
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004240 // Convert to surfaceflinger's internal rotation type.
4241 Transform::orientation_flags rotationFlags;
4242 switch (rotation) {
4243 case ISurfaceComposer::eRotateNone:
4244 rotationFlags = Transform::ROT_0;
4245 break;
4246 case ISurfaceComposer::eRotate90:
4247 rotationFlags = Transform::ROT_90;
4248 break;
4249 case ISurfaceComposer::eRotate180:
4250 rotationFlags = Transform::ROT_180;
4251 break;
4252 case ISurfaceComposer::eRotate270:
4253 rotationFlags = Transform::ROT_270;
4254 break;
4255 default:
4256 rotationFlags = Transform::ROT_0;
4257 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4258 break;
4259 }
4260
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004261 { // Autolock scope
4262 Mutex::Autolock lock(mStateLock);
4263 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4264 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004265 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004266
4267 // create a surface (because we're a producer, and we need to
4268 // dequeue/queue a buffer)
4269 sp<Surface> surface = new Surface(producer, false);
4270
4271 // Put the screenshot Surface into async mode so that
4272 // Layer::headFenceHasSignaled will always return true and we'll latch the
4273 // first buffer regardless of whether or not its acquire fence has
4274 // signaled. This is needed to avoid a race condition in the rotation
4275 // animation. See b/30209608
4276 surface->setAsyncMode(true);
4277
4278 ANativeWindow* window = surface.get();
4279
4280 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4281 if (result != NO_ERROR) {
4282 return result;
4283 }
4284 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4285
4286 ANativeWindowBuffer* buffer = nullptr;
4287 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4288 getRenderEngine().usesWideColor(), &buffer);
4289 if (result != NO_ERROR) {
4290 return result;
4291 }
4292
4293 // This mutex protects syncFd and captureResult for communication of the return values from the
4294 // main thread back to this Binder thread
4295 std::mutex captureMutex;
4296 std::condition_variable captureCondition;
4297 std::unique_lock<std::mutex> captureLock(captureMutex);
4298 int syncFd = -1;
4299 std::optional<status_t> captureResult;
4300
4301 sp<LambdaMessage> message = new LambdaMessage([&]() {
4302 // If there is a refresh pending, bug out early and tell the binder thread to try again
4303 // after the refresh.
4304 if (mRefreshPending) {
4305 ATRACE_NAME("Skipping screenshot for now");
4306 std::unique_lock<std::mutex> captureLock(captureMutex);
4307 captureResult = std::make_optional<status_t>(EAGAIN);
4308 captureCondition.notify_one();
4309 return;
4310 }
4311
4312 status_t result = NO_ERROR;
4313 int fd = -1;
4314 {
4315 Mutex::Autolock _l(mStateLock);
4316 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4317 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4318 minLayerZ, maxLayerZ, useIdentityTransform,
4319 rotationFlags, isLocalScreenshot, &fd);
4320 }
4321
4322 {
4323 std::unique_lock<std::mutex> captureLock(captureMutex);
4324 syncFd = fd;
4325 captureResult = std::make_optional<status_t>(result);
4326 captureCondition.notify_one();
4327 }
4328 });
4329
4330 result = postMessageAsync(message);
4331 if (result == NO_ERROR) {
4332 captureCondition.wait(captureLock, [&]() { return captureResult; });
4333 while (*captureResult == EAGAIN) {
4334 captureResult.reset();
4335 result = postMessageAsync(message);
4336 if (result != NO_ERROR) {
4337 return result;
4338 }
4339 captureCondition.wait(captureLock, [&]() { return captureResult; });
4340 }
4341 result = *captureResult;
4342 }
4343
4344 if (result == NO_ERROR) {
4345 // queueBuffer takes ownership of syncFd
4346 result = window->queueBuffer(window, buffer, syncFd);
4347 }
4348
4349 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004350}
4351
Mathias Agopian180f10d2013-04-10 22:55:41 -07004352
4353void SurfaceFlinger::renderScreenImplLocked(
4354 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004355 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004356 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004357 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004358{
4359 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004360 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004361
4362 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004363 const int32_t hw_w = hw->getWidth();
4364 const int32_t hw_h = hw->getHeight();
4365 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004366 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004367
Dan Stozac1879002014-05-22 15:59:05 -07004368 // if a default or invalid sourceCrop is passed in, set reasonable values
4369 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4370 !sourceCrop.isValid()) {
4371 sourceCrop.setLeftTop(Point(0, 0));
4372 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4373 }
4374
4375 // ensure that sourceCrop is inside screen
4376 if (sourceCrop.left < 0) {
4377 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4378 }
Dan Stozabe31f442014-06-11 11:20:54 -07004379 if (sourceCrop.right > hw_w) {
4380 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004381 }
4382 if (sourceCrop.top < 0) {
4383 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4384 }
Dan Stozabe31f442014-06-11 11:20:54 -07004385 if (sourceCrop.bottom > hw_h) {
4386 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004387 }
4388
Romain Guy88d37dd2017-05-26 17:57:05 -07004389#ifdef USE_HWC2
4390 engine.setWideColor(hw->getWideColorSupport());
4391 engine.setColorMode(hw->getActiveColorMode());
4392#endif
4393
Mathias Agopian180f10d2013-04-10 22:55:41 -07004394 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004395 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004396
4397 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004398 engine.setViewportAndProjection(
4399 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004400 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004401
4402 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004403 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004404
Robert Carr1f0a16a2016-10-24 16:27:39 -07004405 // We loop through the first level of layers without traversing,
4406 // as we need to interpret min/max layer Z in the top level Z space.
4407 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004408 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004409 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004410 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004411 const Layer::State& state(layer->getDrawingState());
4412 if (state.z < minLayerZ || state.z > maxLayerZ) {
4413 continue;
4414 }
Dan Stoza412903f2017-04-27 13:42:17 -07004415 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004416 if (!layer->isVisible()) {
4417 return;
4418 }
4419 if (filtering) layer->setFiltering(true);
4420 layer->draw(hw, useIdentityTransform);
4421 if (filtering) layer->setFiltering(false);
4422 });
4423 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004424
Mathias Agopian931bda12013-08-28 18:11:46 -07004425 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004426}
4427
Dan Stozaabcda352017-06-01 14:37:39 -07004428// A simple RAII class that holds an EGLImage and destroys it either:
4429// a) When the destroy() method is called
4430// b) When the object goes out of scope
4431class ImageHolder {
4432public:
4433 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4434 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004435
Dan Stozaabcda352017-06-01 14:37:39 -07004436 void destroy() {
4437 if (mImage != EGL_NO_IMAGE_KHR) {
4438 eglDestroyImageKHR(mDisplay, mImage);
4439 mImage = EGL_NO_IMAGE_KHR;
4440 }
4441 }
4442
4443private:
4444 const EGLDisplay mDisplay;
4445 EGLImageKHR mImage;
4446};
4447
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004448status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4449 ANativeWindowBuffer* buffer, Rect sourceCrop,
4450 uint32_t reqWidth, uint32_t reqHeight,
4451 int32_t minLayerZ, int32_t maxLayerZ,
4452 bool useIdentityTransform,
4453 Transform::orientation_flags rotation,
4454 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004455 ATRACE_CALL();
4456
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004457 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004458 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004459 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004460 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004461 (state.z < minLayerZ || state.z > maxLayerZ)) {
4462 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004463 }
Dan Stoza412903f2017-04-27 13:42:17 -07004464 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004465 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4466 layer->isSecure());
4467 });
4468 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004469
4470 if (!isLocalScreenshot && secureLayerIsVisible) {
4471 ALOGW("FB is protected: PERMISSION_DENIED");
4472 return PERMISSION_DENIED;
4473 }
4474
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004475 int syncFd = -1;
4476 // create an EGLImage from the buffer so we can later
4477 // turn it into a texture
4478 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4479 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4480 if (image == EGL_NO_IMAGE_KHR) {
4481 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004482 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004483
Dan Stozaabcda352017-06-01 14:37:39 -07004484 // This will automatically destroy the image if we return before calling its destroy method
4485 ImageHolder imageHolder(mEGLDisplay, image);
4486
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004487 // this binds the given EGLImage as a framebuffer for the
4488 // duration of this scope.
4489 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004490 if (imageBond.getStatus() != NO_ERROR) {
4491 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004492 return INVALID_OPERATION;
4493 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004494
Dan Stozaabcda352017-06-01 14:37:39 -07004495 // this will in fact render into our dequeued buffer
4496 // via an FBO, which means we didn't have to create
4497 // an EGLSurface and therefore we're not
4498 // dependent on the context's EGLConfig.
4499 renderScreenImplLocked(
4500 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4501 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004502
Dan Stozaabcda352017-06-01 14:37:39 -07004503 // Attempt to create a sync khr object that can produce a sync point. If that
4504 // isn't available, create a non-dupable sync object in the fallback path and
4505 // wait on it directly.
4506 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4507 if (!DEBUG_SCREENSHOTS) {
4508 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4509 // native fence fd will not be populated until flush() is done.
4510 getRenderEngine().flush();
4511 }
4512
4513 if (sync != EGL_NO_SYNC_KHR) {
4514 // get the sync fd
4515 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4516 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4517 ALOGW("captureScreen: failed to dup sync khr object");
4518 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004519 }
Dan Stozaabcda352017-06-01 14:37:39 -07004520 eglDestroySyncKHR(mEGLDisplay, sync);
4521 } else {
4522 // fallback path
4523 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004524 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004525 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4526 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4527 EGLint eglErr = eglGetError();
4528 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4529 ALOGW("captureScreen: fence wait timed out");
4530 } else {
4531 ALOGW_IF(eglErr != EGL_SUCCESS,
4532 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004533 }
4534 eglDestroySyncKHR(mEGLDisplay, sync);
4535 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004536 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004537 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004538 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004539 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004540
4541 if (DEBUG_SCREENSHOTS) {
4542 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4543 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4544 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4545 hw, minLayerZ, maxLayerZ);
4546 delete [] pixels;
4547 }
4548
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004549 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004550 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004551
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004552 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004553}
4554
Mathias Agopiand5556842013-09-19 17:08:37 -07004555void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004556 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004557 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004558 for (size_t y=0 ; y<h ; y++) {
4559 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4560 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004561 if (p[x] != 0xFF000000) return;
4562 }
4563 }
4564 ALOGE("*** we just took a black screenshot ***\n"
4565 "requested minz=%d, maxz=%d, layerStack=%d",
4566 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004567
Robert Carr2047fae2016-11-28 14:09:09 -08004568 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004569 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004570 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004571 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004572 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004573 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004574 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4575 layer->isVisible() ? '+' : '-',
4576 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004577 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004578 i++;
4579 });
4580 }
4581 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004582 }
4583}
4584
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004585// ---------------------------------------------------------------------------
4586
Dan Stoza412903f2017-04-27 13:42:17 -07004587void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4588 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004589}
4590
Dan Stoza412903f2017-04-27 13:42:17 -07004591void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4592 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004593}
4594
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004595}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004596
4597
4598#if defined(__gl_h_)
4599#error "don't include gl/gl.h in this file"
4600#endif
4601
4602#if defined(__gl2_h_)
4603#error "don't include gl2/gl2.h in this file"
4604#endif