blob: 4157144e3f7c7b5e0b146e6dd88b4868576e341e [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
31#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080040#include <dvr/vr_flinger.h>
41
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060042#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070044#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070045
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080049#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080050#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051
52#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080055
Mathias Agopiancde87a32012-09-13 14:09:01 -070056#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/String8.h>
58#include <utils/String16.h>
59#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070060#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian921e6ac2012-07-23 23:11:29 -070063#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070064#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070070#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093#define DISPLAY_COUNT 1
94
Mathias Agopianfee2b462013-07-03 12:34:01 -070095/*
96 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
97 * black pixels.
98 */
99#define DEBUG_SCREENSHOTS false
100
Jiyong Park00b15b82017-08-10 20:30:56 +0900101extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
Mathias Agopianca088332013-03-28 17:44:13 -0700102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
Steven Thomasb02664d2017-07-26 18:48:28 -0700108namespace {
109class ConditionalLock {
110public:
111 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
112 if (lock) {
113 mMutex.lock();
114 }
115 }
116 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
117private:
118 Mutex& mMutex;
119 bool mLocked;
120};
121} // namespace anonymous
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800131int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
132int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700133bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700134int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700135bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800136uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800137bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800138bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800139int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700158 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700160 mTransactionPending(false),
161 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700162 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700163 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700164 mRepaintEverything(0),
Kalle Raitaa099a242017-01-11 11:17:29 -0800165 mHwcServiceName(getHwcServiceName()),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800166 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800168 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800170 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800171 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800172 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700173 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700174 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700175 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700176 mDebugInSwapBuffers(0),
177 mLastSwapBufferTime(0),
178 mDebugInTransaction(0),
179 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700180 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700181 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800182 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000183 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700184 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700185 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700186 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800187 mHasPoweredOff(false),
188 mFrameBuckets(),
189 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700190 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800191 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700192 mVrFlingerRequestsDisplay(false),
193 mMainThreadId(std::this_thread::get_id()),
194 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800196 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800197
198 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
199 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
200
201 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
202 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
203
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800204 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
205 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700207 useContextPriority = getBool< ISurfaceFlingerConfigs,
208 &ISurfaceFlingerConfigs::useContextPriority>(false);
209
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700210 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
211 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
212
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700213 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
214 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
215
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
217 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
218
Steven Thomas050b2c82017-03-06 11:45:16 -0800219 // Vr flinger is only enabled on Daydream ready devices.
220 useVrFlinger = getBool< ISurfaceFlingerConfigs,
221 &ISurfaceFlingerConfigs::useVrFlinger>(false);
222
Fabien Sanglard1971b632017-03-10 14:50:03 -0800223 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
224 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
225
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600226 hasWideColorDisplay =
227 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
228
Saurabh Shahf4174532017-07-13 10:45:07 -0700229 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
230
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 // debugging stuff...
232 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700233
Mathias Agopianb4b17302013-03-20 18:36:41 -0700234 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700235 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 property_get("debug.sf.showupdates", value, "0");
238 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240 property_get("debug.sf.ddms", value, "0");
241 mDebugDDMS = atoi(value);
242 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700243 if (!startDdmConnection()) {
244 // start failed, and DDMS debugging not enabled
245 mDebugDDMS = 0;
246 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700247 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700248 ALOGI_IF(mDebugRegion, "showupdates enabled");
249 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700250
251 property_get("debug.sf.disable_backpressure", value, "0");
252 mPropagateBackpressure = !atoi(value);
253 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700254
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800255 property_get("debug.sf.enable_hwc_vds", value, "0");
256 mUseHwcVirtualDisplays = atoi(value);
257 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800258
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800259 property_get("ro.sf.disable_triple_buffer", value, "1");
260 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800261 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700262
Romain Guy11d63f42017-07-20 12:47:14 -0700263 // We should be reading 'persist.sys.sf.color_saturation' here
264 // but since /data may be encrypted, we need to wait until after vold
265 // comes online to attempt to read the property. The property is
266 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800267
268 if (useTrebleTestingOverride()) {
269 // Without the override SurfaceFlinger cannot connect to HIDL
270 // services that are not listed in the manifests. Considered
271 // deriving the setting from the set service name, but it
272 // would be brittle if the name that's not 'default' is used
273 // for production purposes later on.
274 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800278void SurfaceFlinger::onFirstRef()
279{
280 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800281}
282
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283SurfaceFlinger::~SurfaceFlinger()
284{
Mathias Agopiana4912602012-07-12 14:25:33 -0700285 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
286 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
287 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288}
289
Dan Stozac7014012014-02-14 15:03:43 -0800290void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800291{
292 // the window manager died on us. prepare its eulogy.
293
Andy McFadden13a082e2012-08-24 10:16:42 -0700294 // restore initial conditions (default device unblank, etc)
295 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800296
297 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700298 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800299}
300
Robert Carr1db73f62016-12-21 12:58:51 -0800301static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700302 status_t err = client->initCheck();
303 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800304 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 }
Robert Carr1db73f62016-12-21 12:58:51 -0800306 return nullptr;
307}
308
309sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
310 return initClient(new Client(this));
311}
312
313sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
314 const sp<IGraphicBufferProducer>& gbp) {
315 if (authenticateSurfaceTexture(gbp) == false) {
316 return nullptr;
317 }
318 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
319 if (layer == nullptr) {
320 return nullptr;
321 }
322
323 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324}
325
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700326sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
327 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700328{
329 class DisplayToken : public BBinder {
330 sp<SurfaceFlinger> flinger;
331 virtual ~DisplayToken() {
332 // no more references, this display must be terminated
333 Mutex::Autolock _l(flinger->mStateLock);
334 flinger->mCurrentState.displays.removeItem(this);
335 flinger->setTransactionFlags(eDisplayTransactionNeeded);
336 }
337 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700338 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700339 : flinger(flinger) {
340 }
341 };
342
343 sp<BBinder> token = new DisplayToken(this);
344
345 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700346 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700347 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700348 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700349 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700350 return token;
351}
352
Jesse Hall6c913be2013-08-08 12:15:49 -0700353void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
354 Mutex::Autolock _l(mStateLock);
355
356 ssize_t idx = mCurrentState.displays.indexOfKey(display);
357 if (idx < 0) {
358 ALOGW("destroyDisplay: invalid display token");
359 return;
360 }
361
362 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
363 if (!info.isVirtualDisplay()) {
364 ALOGE("destroyDisplay called for non-virtual display");
365 return;
366 }
Irvelffc9efc2016-07-27 15:16:37 -0700367 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700368 mCurrentState.displays.removeItemsAt(idx);
369 setTransactionFlags(eDisplayTransactionNeeded);
370}
371
Jesse Hall692c7232012-11-08 15:41:56 -0800372void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800373 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800374 ALOGW_IF(mBuiltinDisplays[type],
375 "Overwriting display token for display type %d", type);
376 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800377 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700378 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800379 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700380 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800381}
382
Mathias Agopiane57f2922012-08-09 16:29:12 -0700383sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700384 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700385 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
386 return NULL;
387 }
Jesse Hall692c7232012-11-08 15:41:56 -0800388 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700389}
390
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800391void SurfaceFlinger::bootFinished()
392{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700393 if (mStartPropertySetThread->join() != NO_ERROR) {
394 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800395 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396 const nsecs_t now = systemTime();
397 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000398 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700399
400 // wait patiently for the window manager death
401 const String16 name("window");
402 sp<IBinder> window(defaultServiceManager()->getService(name));
403 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700404 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700405 }
406
Steven Thomas050b2c82017-03-06 11:45:16 -0800407 if (mVrFlinger) {
408 mVrFlinger->OnBootFinished();
409 }
410
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700411 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700412 // formerly we would just kill the process, but we now ask it to exit so it
413 // can choose where to stop the animation.
414 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700415
416 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
417 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
418 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700419
Thierry Strudel2924d012017-08-14 15:19:37 -0700420 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700421 readPersistentProperties();
422 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700423 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Mathias Agopian3f844832013-08-07 21:24:32 -0700426void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700427 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700428 RenderEngine& engine;
429 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700430 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700431 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
432 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700433 }
434 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700435 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700436 return true;
437 }
438 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700439 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700440}
441
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442class DispSyncSource : public VSyncSource, private DispSync::Callback {
443public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700444 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000445 const char* name) :
446 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700447 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700448 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000449 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
450 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700451 mDispSync(dispSync),
452 mCallbackMutex(),
453 mCallback(),
454 mVsyncMutex(),
455 mPhaseOffset(phaseOffset),
456 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700457
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 virtual ~DispSyncSource() {}
459
460 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700461 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000463 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700464 static_cast<DispSync::Callback*>(this));
465 if (err != NO_ERROR) {
466 ALOGE("error registering vsync callback: %s (%d)",
467 strerror(-err), err);
468 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700469 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470 } else {
471 status_t err = mDispSync->removeEventListener(
472 static_cast<DispSync::Callback*>(this));
473 if (err != NO_ERROR) {
474 ALOGE("error unregistering vsync callback: %s (%d)",
475 strerror(-err), err);
476 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700477 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700478 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700479 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 }
481
482 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700483 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700484 mCallback = callback;
485 }
486
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700487 virtual void setPhaseOffset(nsecs_t phaseOffset) {
488 Mutex::Autolock lock(mVsyncMutex);
489
490 // Normalize phaseOffset to [0, period)
491 auto period = mDispSync->getPeriod();
492 phaseOffset %= period;
493 if (phaseOffset < 0) {
494 // If we're here, then phaseOffset is in (-period, 0). After this
495 // operation, it will be in (0, period)
496 phaseOffset += period;
497 }
498 mPhaseOffset = phaseOffset;
499
500 // If we're not enabled, we don't need to mess with the listeners
501 if (!mEnabled) {
502 return;
503 }
504
505 // Remove the listener with the old offset
506 status_t err = mDispSync->removeEventListener(
507 static_cast<DispSync::Callback*>(this));
508 if (err != NO_ERROR) {
509 ALOGE("error unregistering vsync callback: %s (%d)",
510 strerror(-err), err);
511 }
512
513 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000514 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700515 static_cast<DispSync::Callback*>(this));
516 if (err != NO_ERROR) {
517 ALOGE("error registering vsync callback: %s (%d)",
518 strerror(-err), err);
519 }
520 }
521
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522private:
523 virtual void onDispSyncEvent(nsecs_t when) {
524 sp<VSyncSource::Callback> callback;
525 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700526 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527 callback = mCallback;
528
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700529 if (mTraceVsync) {
530 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700531 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700532 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533 }
534
535 if (callback != NULL) {
536 callback->onVSyncEvent(when);
537 }
538 }
539
Tim Murray4a4e4a22016-04-19 16:29:23 +0000540 const char* const mName;
541
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 int mValue;
543
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700544 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700545 const String8 mVsyncOnLabel;
546 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700547
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700548 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700549
550 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700551 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700552
553 Mutex mVsyncMutex; // Protects the following
554 nsecs_t mPhaseOffset;
555 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700556};
557
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700558class InjectVSyncSource : public VSyncSource {
559public:
560 InjectVSyncSource() {}
561
562 virtual ~InjectVSyncSource() {}
563
564 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
565 std::lock_guard<std::mutex> lock(mCallbackMutex);
566 mCallback = callback;
567 }
568
569 virtual void onInjectSyncEvent(nsecs_t when) {
570 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu6200eac2017-10-05 14:24:41 -0700571 if (mCallback != nullptr) {
572 mCallback->onVSyncEvent(when);
573 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700574 }
575
576 virtual void setVSyncEnabled(bool) {}
577 virtual void setPhaseOffset(nsecs_t) {}
578
579private:
580 std::mutex mCallbackMutex; // Protects the following
581 sp<VSyncSource::Callback> mCallback;
582};
583
Wei Wangf9b05ee2017-07-19 20:59:39 -0700584// Do not call property_set on main thread which will be blocked by init
585// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700586void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700587 ALOGI( "SurfaceFlinger's main thread ready to run. "
588 "Initializing graphics H/W...");
589
Thierry Strudel2924d012017-08-14 15:19:37 -0700590 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900591
Steven Thomasb02664d2017-07-26 18:48:28 -0700592 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800593
Steven Thomasb02664d2017-07-26 18:48:28 -0700594 // initialize EGL for the default display
595 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
596 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800597
Steven Thomasb02664d2017-07-26 18:48:28 -0700598 // start the EventThread
599 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
600 vsyncPhaseOffsetNs, true, "app");
601 mEventThread = new EventThread(vsyncSrc, *this, false);
602 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
603 sfVsyncPhaseOffsetNs, true, "sf");
604 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
605 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800606
Steven Thomasb02664d2017-07-26 18:48:28 -0700607 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
608 struct sched_param param = {0};
609 param.sched_priority = 2;
610 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
611 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
612 }
613 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
614 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800615 }
616
Steven Thomasb02664d2017-07-26 18:48:28 -0700617 // Get a RenderEngine for the given display / config (can't fail)
618 mRenderEngine = RenderEngine::create(mEGLDisplay,
619 HAL_PIXEL_FORMAT_RGBA_8888,
620 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800621
Steven Thomasb02664d2017-07-26 18:48:28 -0700622 // retrieve the EGL context that was selected/created
623 mEGLContext = mRenderEngine->getEGLContext();
624
625 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
626 "couldn't create EGLContext");
627
628 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
629 "Starting with vr flinger active is not currently supported.");
630 mHwc.reset(new HWComposer(mHwcServiceName));
631 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800632
Steven Thomas050b2c82017-03-06 11:45:16 -0800633 if (useVrFlinger) {
634 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700635 // This callback is called from the vr flinger dispatch thread. We
636 // need to call signalTransaction(), which requires holding
637 // mStateLock when we're not on the main thread. Acquiring
638 // mStateLock from the vr flinger dispatch thread might trigger a
639 // deadlock in surface flinger (see b/66916578), so post a message
640 // to be handled on the main thread instead.
641 sp<LambdaMessage> message = new LambdaMessage([=]() {
642 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
643 mVrFlingerRequestsDisplay = requestDisplay;
644 signalTransaction();
645 });
646 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800647 };
648 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
649 vrFlingerRequestDisplayCallback);
650 if (!mVrFlinger) {
651 ALOGE("Failed to start vrflinger");
652 }
653 }
654
Jamie Gennisd1700752013-10-14 12:22:52 -0700655 mEventControlThread = new EventControlThread(this);
656 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
657
Mathias Agopian92a979a2012-08-02 18:32:23 -0700658 // initialize our drawing state
659 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700660
Andy McFadden13a082e2012-08-24 10:16:42 -0700661 // set initial conditions (e.g. unblank default device)
662 initializeDisplays();
663
Dan Stoza4e637772016-07-28 13:31:51 -0700664 mRenderEngine->primeCache();
665
Wei Wangf9b05ee2017-07-19 20:59:39 -0700666 // Inform native graphics APIs whether the present timestamp is supported:
667 if (getHwComposer().hasCapability(
668 HWC2::Capability::PresentFenceIsNotReliable)) {
669 mStartPropertySetThread = new StartPropertySetThread(false);
670 } else {
671 mStartPropertySetThread = new StartPropertySetThread(true);
672 }
673
674 if (mStartPropertySetThread->Start() != NO_ERROR) {
675 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800676 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800677
Dan Stoza9e56aa02015-11-02 13:00:03 -0800678 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700679}
680
Romain Guy11d63f42017-07-20 12:47:14 -0700681void SurfaceFlinger::readPersistentProperties() {
682 char value[PROPERTY_VALUE_MAX];
683
684 property_get("persist.sys.sf.color_saturation", value, "1.0");
685 mSaturation = atof(value);
686 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100687
688 property_get("persist.sys.sf.native_mode", value, "0");
689 mForceNativeColorMode = atoi(value) == 1;
690 if (mForceNativeColorMode) {
691 ALOGV("Forcing native color mode");
692 }
Romain Guy11d63f42017-07-20 12:47:14 -0700693}
694
Mathias Agopiana67e4182012-06-19 17:26:12 -0700695void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800696 // Start boot animation service by setting a property mailbox
697 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800699 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700700 if (mStartPropertySetThread->join() != NO_ERROR) {
701 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800702 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700703}
704
Mathias Agopian875d8e12013-06-07 15:35:48 -0700705size_t SurfaceFlinger::getMaxTextureSize() const {
706 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700707}
708
Mathias Agopian875d8e12013-06-07 15:35:48 -0700709size_t SurfaceFlinger::getMaxViewportDims() const {
710 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700711}
712
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800713// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800714
Jamie Gennis582270d2011-08-17 18:19:00 -0700715bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800716 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800717 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800718 return authenticateSurfaceTextureLocked(bufferProducer);
719}
720
721bool SurfaceFlinger::authenticateSurfaceTextureLocked(
722 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800723 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700724 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800725}
726
Brian Anderson6b376712017-04-04 10:51:39 -0700727status_t SurfaceFlinger::getSupportedFrameTimestamps(
728 std::vector<FrameEvent>* outSupported) const {
729 *outSupported = {
730 FrameEvent::REQUESTED_PRESENT,
731 FrameEvent::ACQUIRE,
732 FrameEvent::LATCH,
733 FrameEvent::FIRST_REFRESH_START,
734 FrameEvent::LAST_REFRESH_START,
735 FrameEvent::GPU_COMPOSITION_DONE,
736 FrameEvent::DEQUEUE_READY,
737 FrameEvent::RELEASE,
738 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700739 ConditionalLock _l(mStateLock,
740 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700741 if (!getHwComposer().hasCapability(
742 HWC2::Capability::PresentFenceIsNotReliable)) {
743 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
744 }
745 return NO_ERROR;
746}
747
Dan Stoza7f7da322014-05-02 15:26:25 -0700748status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
749 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700750 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700751 return BAD_VALUE;
752 }
753
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500754 if (!display.get())
755 return NAME_NOT_FOUND;
756
Jesse Hall692c7232012-11-08 15:41:56 -0800757 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700758 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800759 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700760 type = i;
761 break;
762 }
763 }
764
765 if (type < 0) {
766 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700767 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700768
Mathias Agopian8b736f12012-08-13 17:54:26 -0700769 // TODO: Not sure if display density should handled by SF any longer
770 class Density {
771 static int getDensityFromProperty(char const* propName) {
772 char property[PROPERTY_VALUE_MAX];
773 int density = 0;
774 if (property_get(propName, property, NULL) > 0) {
775 density = atoi(property);
776 }
777 return density;
778 }
779 public:
780 static int getEmuDensity() {
781 return getDensityFromProperty("qemu.sf.lcd_density"); }
782 static int getBuildDensity() {
783 return getDensityFromProperty("ro.sf.lcd_density"); }
784 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700785
Dan Stoza7f7da322014-05-02 15:26:25 -0700786 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700787
Steven Thomas6d8110b2017-08-31 18:24:21 -0700788 ConditionalLock _l(mStateLock,
789 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800790 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700791 DisplayInfo info = DisplayInfo();
792
Dan Stoza9e56aa02015-11-02 13:00:03 -0800793 float xdpi = hwConfig->getDpiX();
794 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700795
796 if (type == DisplayDevice::DISPLAY_PRIMARY) {
797 // The density of the device is provided by a build property
798 float density = Density::getBuildDensity() / 160.0f;
799 if (density == 0) {
800 // the build doesn't provide a density -- this is wrong!
801 // use xdpi instead
802 ALOGE("ro.sf.lcd_density must be defined as a build property");
803 density = xdpi / 160.0f;
804 }
805 if (Density::getEmuDensity()) {
806 // if "qemu.sf.lcd_density" is specified, it overrides everything
807 xdpi = ydpi = density = Density::getEmuDensity();
808 density /= 160.0f;
809 }
810 info.density = density;
811
812 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700813 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000814 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700815 } else {
816 // TODO: where should this value come from?
817 static const int TV_DENSITY = 213;
818 info.density = TV_DENSITY / 160.0f;
819 info.orientation = 0;
820 }
821
Dan Stoza9e56aa02015-11-02 13:00:03 -0800822 info.w = hwConfig->getWidth();
823 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 info.xdpi = xdpi;
825 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900827 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828
Andy McFadden91b2ca82014-06-13 14:04:23 -0700829 // This is how far in advance a buffer must be queued for
830 // presentation at a given time. If you want a buffer to appear
831 // on the screen at time N, you must submit the buffer before
832 // (N - presentationDeadline).
833 //
834 // Normally it's one full refresh period (to give SF a chance to
835 // latch the buffer), but this can be reduced by configuring a
836 // DispSync offset. Any additional delays introduced by the hardware
837 // composer or panel must be accounted for here.
838 //
839 // We add an additional 1ms to allow for processing time and
840 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800842 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700843
844 // All non-virtual displays are currently considered secure.
845 info.secure = true;
846
Michael Wright28f24d02016-07-12 13:30:53 -0700847 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700848 }
849
Dan Stoza7f7da322014-05-02 15:26:25 -0700850 return NO_ERROR;
851}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700852
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800853status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700854 DisplayStatInfo* stats) {
855 if (stats == NULL) {
856 return BAD_VALUE;
857 }
858
859 // FIXME for now we always return stats for the primary display
860 memset(stats, 0, sizeof(*stats));
861 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
862 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
863 return NO_ERROR;
864}
865
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700866int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800867 if (display == NULL) {
868 ALOGE("%s : display is NULL", __func__);
869 return BAD_VALUE;
870 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700871
872 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700873 if (device != NULL) {
874 return device->getActiveConfig();
875 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700876
Dan Stoza24a42e92015-03-09 10:04:11 -0700877 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700878}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700879
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700880void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
881 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
882 this);
883 int32_t type = hw->getDisplayType();
884 int currentMode = hw->getActiveConfig();
885
886 if (mode == currentMode) {
887 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
888 return;
889 }
890
891 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
892 ALOGW("Trying to set config for virtual display");
893 return;
894 }
895
896 hw->setActiveConfig(mode);
897 getHwComposer().setActiveConfig(type, mode);
898}
899
900status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
901 class MessageSetActiveConfig: public MessageBase {
902 SurfaceFlinger& mFlinger;
903 sp<IBinder> mDisplay;
904 int mMode;
905 public:
906 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
907 int mode) :
908 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
909 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700910 Vector<DisplayInfo> configs;
911 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700912 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700913 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700914 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700915 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700916 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700917 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
918 if (hw == NULL) {
919 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700920 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700921 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
922 ALOGW("Attempt to set active config = %d for virtual display",
923 mMode);
924 } else {
925 mFlinger.setActiveConfigInternal(hw, mMode);
926 }
927 return true;
928 }
929 };
930 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
931 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700932 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700933}
Michael Wright28f24d02016-07-12 13:30:53 -0700934status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
935 Vector<android_color_mode_t>* outColorModes) {
936 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
937 return BAD_VALUE;
938 }
939
940 if (!display.get()) {
941 return NAME_NOT_FOUND;
942 }
943
944 int32_t type = NAME_NOT_FOUND;
945 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
946 if (display == mBuiltinDisplays[i]) {
947 type = i;
948 break;
949 }
950 }
951
952 if (type < 0) {
953 return type;
954 }
955
Steven Thomas6d8110b2017-08-31 18:24:21 -0700956 std::vector<android_color_mode_t> modes;
957 {
958 ConditionalLock _l(mStateLock,
959 std::this_thread::get_id() != mMainThreadId);
960 modes = getHwComposer().getColorModes(type);
961 }
Michael Wright28f24d02016-07-12 13:30:53 -0700962 outColorModes->clear();
963 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
964
965 return NO_ERROR;
966}
967
968android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700969 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700970 if (device != nullptr) {
971 return device->getActiveColorMode();
972 }
973 return static_cast<android_color_mode_t>(BAD_VALUE);
974}
975
976void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
977 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700978 int32_t type = hw->getDisplayType();
979 android_color_mode_t currentMode = hw->getActiveColorMode();
980
981 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700982 return;
983 }
984
985 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
986 ALOGW("Trying to set config for virtual display");
987 return;
988 }
989
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600990 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
991 hw->getDisplayType());
992
Michael Wright28f24d02016-07-12 13:30:53 -0700993 hw->setActiveColorMode(mode);
994 getHwComposer().setActiveColorMode(type, mode);
995}
996
997
998status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
999 android_color_mode_t colorMode) {
1000 class MessageSetActiveColorMode: public MessageBase {
1001 SurfaceFlinger& mFlinger;
1002 sp<IBinder> mDisplay;
1003 android_color_mode_t mMode;
1004 public:
1005 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1006 android_color_mode_t mode) :
1007 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1008 virtual bool handler() {
1009 Vector<android_color_mode_t> modes;
1010 mFlinger.getDisplayColorModes(mDisplay, &modes);
1011 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1012 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001013 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1014 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001015 return true;
1016 }
1017 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1018 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001019 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1020 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001021 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001022 ALOGW("Attempt to set active color mode %s %d for virtual display",
1023 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001024 } else {
1025 mFlinger.setActiveColorModeInternal(hw, mMode);
1026 }
1027 return true;
1028 }
1029 };
1030 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1031 postMessageSync(msg);
1032 return NO_ERROR;
1033}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001034
Svetoslavd85084b2014-03-20 10:28:31 -07001035status_t SurfaceFlinger::clearAnimationFrameStats() {
1036 Mutex::Autolock _l(mStateLock);
1037 mAnimFrameTracker.clearStats();
1038 return NO_ERROR;
1039}
1040
1041status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1042 Mutex::Autolock _l(mStateLock);
1043 mAnimFrameTracker.getStats(outStats);
1044 return NO_ERROR;
1045}
1046
Dan Stozac4f471e2016-03-24 09:31:08 -07001047status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1048 HdrCapabilities* outCapabilities) const {
1049 Mutex::Autolock _l(mStateLock);
1050
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001051 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001052 if (displayDevice == nullptr) {
1053 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1054 return BAD_VALUE;
1055 }
1056
1057 std::unique_ptr<HdrCapabilities> capabilities =
1058 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1059 if (capabilities) {
1060 std::swap(*outCapabilities, *capabilities);
1061 } else {
1062 return BAD_VALUE;
1063 }
1064
1065 return NO_ERROR;
1066}
1067
Chia-I Wu6200eac2017-10-05 14:24:41 -07001068void SurfaceFlinger::enableVSyncInjectionsInternal(bool enable) {
1069 Mutex::Autolock _l(mStateLock);
1070
1071 if (mInjectVSyncs == enable) {
1072 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001073 }
1074
1075 if (enable) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001076 ALOGV("VSync Injections enabled");
1077 if (mVSyncInjector.get() == nullptr) {
1078 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001079 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001080 }
1081 mEventQueue.setEventThread(mInjectorEventThread);
1082 } else {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001083 ALOGV("VSync Injections disabled");
1084 mEventQueue.setEventThread(mSFEventThread);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001085 }
Chia-I Wu6200eac2017-10-05 14:24:41 -07001086
1087 mInjectVSyncs = enable;
1088}
1089
1090status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1091 class MessageEnableVSyncInjections : public MessageBase {
1092 SurfaceFlinger* mFlinger;
1093 bool mEnable;
1094 public:
1095 MessageEnableVSyncInjections(SurfaceFlinger* flinger, bool enable)
1096 : mFlinger(flinger), mEnable(enable) { }
1097 virtual bool handler() {
1098 mFlinger->enableVSyncInjectionsInternal(mEnable);
1099 return true;
1100 }
1101 };
1102 sp<MessageBase> msg = new MessageEnableVSyncInjections(this, enable);
1103 postMessageSync(msg);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001104 return NO_ERROR;
1105}
1106
1107status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu6200eac2017-10-05 14:24:41 -07001108 Mutex::Autolock _l(mStateLock);
1109
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001110 if (!mInjectVSyncs) {
1111 ALOGE("VSync Injections not enabled");
1112 return BAD_VALUE;
1113 }
1114 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1115 ALOGV("Injecting VSync inside SurfaceFlinger");
1116 mVSyncInjector->onInjectSyncEvent(when);
1117 }
1118 return NO_ERROR;
1119}
1120
Kalle Raitaa099a242017-01-11 11:17:29 -08001121status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1122 IPCThreadState* ipc = IPCThreadState::self();
1123 const int pid = ipc->getCallingPid();
1124 const int uid = ipc->getCallingUid();
1125 if ((uid != AID_SHELL) &&
1126 !PermissionCache::checkPermission(sDump, pid, uid)) {
1127 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1128 return PERMISSION_DENIED;
1129 }
1130
1131 // Try to acquire a lock for 1s, fail gracefully
1132 const status_t err = mStateLock.timedLock(s2ns(1));
1133 const bool locked = (err == NO_ERROR);
1134 if (!locked) {
1135 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1136 return TIMED_OUT;
1137 }
1138
1139 outLayers->clear();
1140 mCurrentState.traverseInZOrder([&](Layer* layer) {
1141 outLayers->push_back(layer->getLayerDebugInfo());
1142 });
1143
1144 mStateLock.unlock();
1145 return NO_ERROR;
1146}
1147
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001148// ----------------------------------------------------------------------------
1149
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001150sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1151 ISurfaceComposer::VsyncSource vsyncSource) {
1152 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1153 return mSFEventThread->createEventConnection();
1154 } else {
1155 return mEventThread->createEventConnection();
1156 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001157}
1158
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001159// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001160
1161void SurfaceFlinger::waitForEvent() {
1162 mEventQueue.waitMessage();
1163}
1164
1165void SurfaceFlinger::signalTransaction() {
1166 mEventQueue.invalidate();
1167}
1168
1169void SurfaceFlinger::signalLayerUpdate() {
1170 mEventQueue.invalidate();
1171}
1172
1173void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001174 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001175 mEventQueue.refresh();
1176}
1177
1178status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001179 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001180 return mEventQueue.postMessage(msg, reltime);
1181}
1182
1183status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001184 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001185 status_t res = mEventQueue.postMessage(msg, reltime);
1186 if (res == NO_ERROR) {
1187 msg->wait();
1188 }
1189 return res;
1190}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001191
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001192void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001193 do {
1194 waitForEvent();
1195 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001196}
1197
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001198void SurfaceFlinger::enableHardwareVsync() {
1199 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001200 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001201 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001202 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1203 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001204 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001205 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001206}
1207
Jesse Hall948fe0c2013-10-14 12:56:09 -07001208void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001209 Mutex::Autolock _l(mHWVsyncLock);
1210
Jesse Hall948fe0c2013-10-14 12:56:09 -07001211 if (makeAvailable) {
1212 mHWVsyncAvailable = true;
1213 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001214 // Hardware vsync is not currently available, so abort the resync
1215 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001216 return;
1217 }
1218
Dan Stoza9e56aa02015-11-02 13:00:03 -08001219 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1220 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221
1222 mPrimaryDispSync.reset();
1223 mPrimaryDispSync.setPeriod(period);
1224
1225 if (!mPrimaryHWVsyncEnabled) {
1226 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001227 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1228 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001229 mPrimaryHWVsyncEnabled = true;
1230 }
1231}
1232
Jesse Hall948fe0c2013-10-14 12:56:09 -07001233void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001234 Mutex::Autolock _l(mHWVsyncLock);
1235 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001236 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1237 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238 mPrimaryDispSync.endResync();
1239 mPrimaryHWVsyncEnabled = false;
1240 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001241 if (makeUnavailable) {
1242 mHWVsyncAvailable = false;
1243 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001244}
1245
Tim Murray4a4e4a22016-04-19 16:29:23 +00001246void SurfaceFlinger::resyncWithRateLimit() {
1247 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001248
1249 // No explicit locking is needed here since EventThread holds a lock while calling this method
1250 static nsecs_t sLastResyncAttempted = 0;
1251 const nsecs_t now = systemTime();
1252 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001253 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001254 }
Dan Stoza57164302017-05-08 14:03:54 -07001255 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001256}
1257
Steven Thomasb02664d2017-07-26 18:48:28 -07001258void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1259 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001260 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001261 // Ignore any vsyncs from a previous hardware composer.
1262 if (sequenceId != mComposerSequenceId) {
1263 return;
1264 }
1265
1266 int32_t type;
1267 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001268 return;
1269 }
1270
Jamie Gennisd1700752013-10-14 12:22:52 -07001271 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001272
Jamie Gennisd1700752013-10-14 12:22:52 -07001273 { // Scope for the lock
1274 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001275 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001276 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001278 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001279
1280 if (needsHwVsync) {
1281 enableHardwareVsync();
1282 } else {
1283 disableHardwareVsync(false);
1284 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001285}
1286
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001287void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001288 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001289 *compositorTiming = mCompositorTiming;
1290}
1291
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001292void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001293 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001294 wp<IBinder> token = mBuiltinDisplays[type];
1295
1296 // All non-virtual displays are currently considered secure.
1297 const bool isSecure = true;
1298
1299 sp<IGraphicBufferProducer> producer;
1300 sp<IGraphicBufferConsumer> consumer;
1301 BufferQueue::createBufferQueue(&producer, &consumer);
1302
1303 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1304
1305 bool hasWideColorModes = false;
1306 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1307 for (android_color_mode_t colorMode : modes) {
1308 switch (colorMode) {
1309 case HAL_COLOR_MODE_DISPLAY_P3:
1310 case HAL_COLOR_MODE_ADOBE_RGB:
1311 case HAL_COLOR_MODE_DCI_P3:
1312 hasWideColorModes = true;
1313 break;
1314 default:
1315 break;
1316 }
1317 }
Romain Guy54f154a2017-10-24 21:40:32 +01001318 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001319 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1320 token, fbs, producer, mRenderEngine->getEGLConfig(),
Romain Guy54f154a2017-10-24 21:40:32 +01001321 useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001322 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001323 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001324 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001325 defaultColorMode = HAL_COLOR_MODE_SRGB;
1326 }
1327 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001328 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001329
1330 // Add the primary display token to mDrawingState so we don't try to
1331 // recreate the DisplayDevice for the primary display.
1332 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1333
1334 // make the GLContext current so that we can create textures when creating
1335 // Layers (which may happens before we render something)
1336 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001337}
1338
Steven Thomasb02664d2017-07-26 18:48:28 -07001339void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1340 hwc2_display_t display, HWC2::Connection connection,
1341 bool primaryDisplay) {
1342 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1343 sequenceId, display,
1344 connection == HWC2::Connection::Connected ?
1345 "connected" : "disconnected",
1346 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001347
Steven Thomasb02664d2017-07-26 18:48:28 -07001348 // Only lock if we're not on the main thread. This function is normally
1349 // called on a hwbinder thread, but for the primary display it's called on
1350 // the main thread with the state lock already held, so don't attempt to
1351 // acquire it here.
1352 ConditionalLock lock(mStateLock,
1353 std::this_thread::get_id() != mMainThreadId);
1354
1355 if (primaryDisplay) {
1356 mHwc->onHotplug(display, connection);
1357 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1358 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001360 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001361 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 if (sequenceId != mComposerSequenceId) {
1363 return;
1364 }
1365 if (mHwc->isUsingVrComposer()) {
1366 ALOGE("External displays are not supported by the vr hardware composer.");
1367 return;
1368 }
1369 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001370 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001372 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001373 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001374 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1375 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001376 }
1377 setTransactionFlags(eDisplayTransactionNeeded);
1378
Andy McFadden9e9689c2012-10-10 18:17:51 -07001379 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001380 }
Mathias Agopian86303202012-07-24 22:46:10 -07001381}
1382
Steven Thomasb02664d2017-07-26 18:48:28 -07001383void SurfaceFlinger::onRefreshReceived(int sequenceId,
1384 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001385 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 if (sequenceId != mComposerSequenceId) {
1387 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001388 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001389 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001390}
1391
Dan Stoza9e56aa02015-11-02 13:00:03 -08001392void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001393 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001394 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001395 getHwComposer().setVsyncEnabled(disp,
1396 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001397}
1398
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001400void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402 // Clear the drawing state so that the logic inside of
1403 // handleTransactionLocked will fire. It will determine the delta between
1404 // mCurrentState and mDrawingState and re-apply all changes when we make the
1405 // transition.
1406 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001408 mDisplays.clear();
1409}
1410
Steven Thomas050b2c82017-03-06 11:45:16 -08001411void SurfaceFlinger::updateVrFlinger() {
1412 if (!mVrFlinger)
1413 return;
1414 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1415 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001416 return;
1417 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1420 ALOGE("Vr flinger is only supported for remote hardware composer"
1421 " service connections. Ignoring request to transition to vr"
1422 " flinger.");
1423 mVrFlingerRequestsDisplay = false;
1424 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001425 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001426
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001427 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001428
Steven Thomasb02664d2017-07-26 18:48:28 -07001429 int currentDisplayPowerMode = getDisplayDeviceLocked(
1430 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001433 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001435
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 resetDisplayState();
1437 mHwc.reset(); // Delete the current instance before creating the new one
1438 mHwc.reset(new HWComposer(
1439 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1440 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1443 "Switched to non-remote hardware composer");
1444
1445 if (vrFlingerRequestsDisplay) {
1446 mVrFlinger->GrantDisplayOwnership();
1447 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001448 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001449 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001450
1451 mVisibleRegionsDirty = true;
1452 invalidateHwcGeometry();
1453
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001454 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1456 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1457 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001458
Steven Thomasb02664d2017-07-26 18:48:28 -07001459 // Reset the timing values to account for the period of the swapped in HWC
1460 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1461 const nsecs_t period = activeConfig->getVsyncPeriod();
1462 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001463
Steven Thomasb02664d2017-07-26 18:48:28 -07001464 // Use phase of 0 since phase is not known.
1465 // Use latency of 0, which will snap to the ideal latency.
1466 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001467
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001468 android_atomic_or(1, &mRepaintEverything);
1469 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001470}
1471
Mathias Agopian4fec8732012-06-29 14:12:52 -07001472void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001473 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001474 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001475 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001476 bool frameMissed = !mHadClientComposition &&
1477 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001478 (mPreviousPresentFence->getSignalTime() ==
1479 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001480 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001481 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001482 signalLayerUpdate();
1483 break;
1484 }
1485
Steven Thomas050b2c82017-03-06 11:45:16 -08001486 // Now that we're going to make it to the handleMessageTransaction()
1487 // call below it's safe to call updateVrFlinger(), which will
1488 // potentially trigger a display handoff.
1489 updateVrFlinger();
1490
Dan Stoza6b9454d2014-11-07 16:00:59 -08001491 bool refreshNeeded = handleMessageTransaction();
1492 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001493 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001494 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001495 // Signal a refresh if a transaction modified the window state,
1496 // a new buffer was latched, or if HWC has requested a full
1497 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001498 signalRefresh();
1499 }
1500 break;
1501 }
1502 case MessageQueue::REFRESH: {
1503 handleMessageRefresh();
1504 break;
1505 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001506 }
1507}
1508
Dan Stoza6b9454d2014-11-07 16:00:59 -08001509bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001510 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001511 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001512 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001513 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001514 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001515 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516}
1517
Dan Stoza6b9454d2014-11-07 16:00:59 -08001518bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001520 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001521}
1522
1523void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001525
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001526 mRefreshPending = false;
1527
Pablo Ceballos40845df2016-01-25 17:41:15 -08001528 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001529
Brian Andersond6927fb2016-07-23 23:37:30 -07001530 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001531 rebuildLayerStacks();
1532 setUpHWComposer();
1533 doDebugFlashRegions();
1534 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001535 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001536
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001537 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001538
1539 mHadClientComposition = false;
1540 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1541 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1542 mHadClientComposition = mHadClientComposition ||
1543 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1544 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001545
Dan Stoza9e56aa02015-11-02 13:00:03 -08001546 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001548
Mathias Agopiancd60f992012-08-16 16:28:27 -07001549void SurfaceFlinger::doDebugFlashRegions()
1550{
1551 // is debugging enabled
1552 if (CC_LIKELY(!mDebugRegion))
1553 return;
1554
1555 const bool repaintEverything = mRepaintEverything;
1556 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1557 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001558 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559 // transform the dirty region into this screen's coordinate space
1560 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1561 if (!dirtyRegion.isEmpty()) {
1562 // redraw the whole screen
1563 doComposeSurfaces(hw, Region(hw->bounds()));
1564
1565 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001567 RenderEngine& engine(getRenderEngine());
1568 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1569
Mathias Agopianda27af92012-09-13 18:17:13 -07001570 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001571 }
1572 }
1573 }
1574
1575 postFramebuffer();
1576
1577 if (mDebugRegion > 1) {
1578 usleep(mDebugRegion * 1000);
1579 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001580
Dan Stoza9e56aa02015-11-02 13:00:03 -08001581 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001582 auto& displayDevice = mDisplays[displayId];
1583 if (!displayDevice->isDisplayOn()) {
1584 continue;
1585 }
1586
1587 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001588 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1589 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001590 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001591}
1592
Brian Andersond6927fb2016-07-23 23:37:30 -07001593void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001594{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001595 ATRACE_CALL();
1596 ALOGV("preComposition");
1597
Mathias Agopiancd60f992012-08-16 16:28:27 -07001598 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001599 mDrawingState.traverseInZOrder([&](Layer* layer) {
1600 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001601 needExtraInvalidate = true;
1602 }
Robert Carr2047fae2016-11-28 14:09:09 -08001603 });
1604
Mathias Agopiancd60f992012-08-16 16:28:27 -07001605 if (needExtraInvalidate) {
1606 signalLayerUpdate();
1607 }
1608}
1609
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001610void SurfaceFlinger::updateCompositorTiming(
1611 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1612 std::shared_ptr<FenceTime>& presentFenceTime) {
1613 // Update queue of past composite+present times and determine the
1614 // most recently known composite to present latency.
1615 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1616 nsecs_t compositeToPresentLatency = -1;
1617 while (!mCompositePresentTimes.empty()) {
1618 CompositePresentTime& cpt = mCompositePresentTimes.front();
1619 // Cached values should have been updated before calling this method,
1620 // which helps avoid duplicate syscalls.
1621 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1622 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1623 break;
1624 }
1625 compositeToPresentLatency = displayTime - cpt.composite;
1626 mCompositePresentTimes.pop();
1627 }
1628
1629 // Don't let mCompositePresentTimes grow unbounded, just in case.
1630 while (mCompositePresentTimes.size() > 16) {
1631 mCompositePresentTimes.pop();
1632 }
1633
Brian Andersond0010582017-03-07 13:20:31 -08001634 setCompositorTimingSnapped(
1635 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1636}
1637
1638void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1639 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001640 // Integer division and modulo round toward 0 not -inf, so we need to
1641 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001642 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001643 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1644 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1645
Brian Andersond0010582017-03-07 13:20:31 -08001646 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1647 if (idealLatency <= 0) {
1648 idealLatency = vsyncInterval;
1649 }
1650
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001651 // Snap the latency to a value that removes scheduling jitter from the
1652 // composition and present times, which often have >1ms of jitter.
1653 // Reducing jitter is important if an app attempts to extrapolate
1654 // something (such as user input) to an accurate diasplay time.
1655 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1656 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001657 nsecs_t bias = vsyncInterval / 2;
1658 int64_t extraVsyncs =
1659 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1660 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1661 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001662
Brian Andersond0010582017-03-07 13:20:31 -08001663 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001664 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1665 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001666 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001667}
1668
1669void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001670{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001671 ATRACE_CALL();
1672 ALOGV("postComposition");
1673
Brian Anderson3546a3f2016-07-14 11:51:14 -07001674 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001675 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001676 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001677 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001678 }
1679
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001680 // |mStateLock| not needed as we are on the main thread
1681 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001682
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001683 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001684 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1685 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1686 glCompositionDoneFenceTime =
1687 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1688 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1689 } else {
1690 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1691 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001692
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001693 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001694 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1695 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1696 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001697
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001698 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1699 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1700
1701 // We use the refreshStartTime which might be sampled a little later than
1702 // when we started doing work for this frame, but that should be okay
1703 // since updateCompositorTiming has snapping logic.
1704 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001705 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001706 CompositorTiming compositorTiming;
1707 {
1708 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1709 compositorTiming = mCompositorTiming;
1710 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001711
Robert Carr2047fae2016-11-28 14:09:09 -08001712 mDrawingState.traverseInZOrder([&](Layer* layer) {
1713 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001714 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001715 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001716 recordBufferingStats(layer->getName().string(),
1717 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001718 }
Robert Carr2047fae2016-11-28 14:09:09 -08001719 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001720
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001721 if (presentFenceTime->isValid()) {
1722 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001723 enableHardwareVsync();
1724 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001725 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001726 }
1727 }
1728
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001729 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001730 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001731 enableHardwareVsync();
1732 }
1733 }
1734
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001735 if (mAnimCompositionPending) {
1736 mAnimCompositionPending = false;
1737
Brian Anderson4e606e32017-03-16 15:34:57 -07001738 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001739 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001740 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001741 } else {
1742 // The HWC doesn't support present fences, so use the refresh
1743 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001744 nsecs_t presentTime =
1745 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001746 mAnimFrameTracker.setActualPresentTime(presentTime);
1747 }
1748 mAnimFrameTracker.advanceFrame();
1749 }
Dan Stozab90cf072015-03-05 11:05:59 -08001750
1751 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1752 return;
1753 }
1754
1755 nsecs_t currentTime = systemTime();
1756 if (mHasPoweredOff) {
1757 mHasPoweredOff = false;
1758 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001759 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001760 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001761 if (numPeriods < NUM_BUCKETS - 1) {
1762 mFrameBuckets[numPeriods] += elapsedTime;
1763 } else {
1764 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1765 }
1766 mTotalTime += elapsedTime;
1767 }
1768 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001769}
1770
1771void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001772 ATRACE_CALL();
1773 ALOGV("rebuildLayerStacks");
1774
Mathias Agopiancd60f992012-08-16 16:28:27 -07001775 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001776 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1777 ATRACE_CALL();
1778 mVisibleRegionsDirty = false;
1779 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001780
Jeff Sharkey76488112017-02-27 14:15:18 -07001781 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1782 Region opaqueRegion;
1783 Region dirtyRegion;
1784 Vector<sp<Layer>> layersSortedByZ;
1785 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1786 const Transform& tr(displayDevice->getTransform());
1787 const Rect bounds(displayDevice->getBounds());
1788 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001789 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001790
Jeff Sharkey76488112017-02-27 14:15:18 -07001791 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001792 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1793 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001794 Region drawRegion(tr.transform(
1795 layer->visibleNonTransparentRegion));
1796 drawRegion.andSelf(bounds);
1797 if (!drawRegion.isEmpty()) {
1798 layersSortedByZ.add(layer);
1799 } else {
1800 // Clear out the HWC layer if this layer was
1801 // previously visible, but no longer is
Steven Thomasb02664d2017-07-26 18:48:28 -07001802 layer->destroyHwcLayer(
1803 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001804 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001805 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001806 // WM changes displayDevice->layerStack upon sleep/awake.
1807 // Here we make sure we delete the HWC layers even if
1808 // WM changed their layer stack.
Steven Thomasb02664d2017-07-26 18:48:28 -07001809 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001810 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001811 });
1812 }
1813 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1814 displayDevice->undefinedRegion.set(bounds);
1815 displayDevice->undefinedRegion.subtractSelf(
1816 tr.transform(opaqueRegion));
1817 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001818 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001819 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001820}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001821
Romain Guy0147a172017-06-01 13:53:56 -07001822mat4 SurfaceFlinger::computeSaturationMatrix() const {
1823 if (mSaturation == 1.0f) {
1824 return mat4();
1825 }
1826
1827 // Rec.709 luma coefficients
1828 float3 luminance{0.213f, 0.715f, 0.072f};
1829 luminance *= 1.0f - mSaturation;
1830 return mat4(
1831 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1832 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1833 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1834 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1835 );
1836}
1837
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001838// pickColorMode translates a given dataspace into the best available color mode.
1839// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001840android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001841 if (mForceNativeColorMode) {
1842 return HAL_COLOR_MODE_NATIVE;
1843 }
1844
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001845 switch (dataSpace) {
1846 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1847 // system expects.
1848 case HAL_DATASPACE_UNKNOWN:
1849 case HAL_DATASPACE_SRGB:
1850 case HAL_DATASPACE_V0_SRGB:
1851 return HAL_COLOR_MODE_SRGB;
1852 break;
1853
1854 case HAL_DATASPACE_DISPLAY_P3:
1855 return HAL_COLOR_MODE_DISPLAY_P3;
1856 break;
1857
1858 default:
1859 // TODO (courtneygo): Do we want to assert an error here?
1860 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1861 dataSpace);
1862 return HAL_COLOR_MODE_SRGB;
1863 break;
1864 }
1865}
1866
Romain Guy0147a172017-06-01 13:53:56 -07001867android_dataspace SurfaceFlinger::bestTargetDataSpace(
1868 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001869 // Only support sRGB and Display-P3 right now.
1870 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1871 return HAL_DATASPACE_DISPLAY_P3;
1872 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001873 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1874 return HAL_DATASPACE_DISPLAY_P3;
1875 }
1876 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1877 return HAL_DATASPACE_DISPLAY_P3;
1878 }
1879
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001880 return HAL_DATASPACE_V0_SRGB;
1881}
1882
Mathias Agopiancd60f992012-08-16 16:28:27 -07001883void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001884 ATRACE_CALL();
1885 ALOGV("setUpHWComposer");
1886
Jesse Hall028dc8f2013-08-20 16:35:32 -07001887 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001888 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1889 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1890 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1891
1892 // If nothing has changed (!dirty), don't recompose.
1893 // If something changed, but we don't currently have any visible layers,
1894 // and didn't when we last did a composition, then skip it this time.
1895 // The second rule does two things:
1896 // - When all layers are removed from a display, we'll emit one black
1897 // frame, then nothing more until we get new layers.
1898 // - When a display is created with a private layer stack, we won't
1899 // emit any black frames until a layer is added to the layer stack.
1900 bool mustRecompose = dirty && !(empty && wasEmpty);
1901
1902 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1903 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1904 mustRecompose ? "doing" : "skipping",
1905 dirty ? "+" : "-",
1906 empty ? "+" : "-",
1907 wasEmpty ? "+" : "-");
1908
Dan Stoza71433162014-02-04 16:22:36 -08001909 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001910
1911 if (mustRecompose) {
1912 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1913 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001914 }
1915
Dan Stoza9e56aa02015-11-02 13:00:03 -08001916 // build the h/w work list
1917 if (CC_UNLIKELY(mGeometryInvalid)) {
1918 mGeometryInvalid = false;
1919 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1920 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1921 const auto hwcId = displayDevice->getHwcDisplayId();
1922 if (hwcId >= 0) {
1923 const Vector<sp<Layer>>& currentLayers(
1924 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001925 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001926 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001927 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001928 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001929 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001930 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001931 }
1932 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001933
Robert Carrae060832016-11-28 10:51:00 -08001934 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001935 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001936 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001937 }
1938 }
1939 }
1940 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001941 }
Riley Andrews03414a12014-07-01 14:22:59 -07001942
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001943
Romain Guy0147a172017-06-01 13:53:56 -07001944 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001945
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946 // Set the per-frame data
1947 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1948 auto& displayDevice = mDisplays[displayId];
1949 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001950
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951 if (hwcId < 0) {
1952 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001953 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001954 if (colorMatrix != mPreviousColorMatrix) {
1955 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1956 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1957 "display %zd: %d", displayId, result);
1958 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001959 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1960 layer->setPerFrameData(displayDevice);
1961 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001962
1963 if (hasWideColorDisplay) {
1964 android_color_mode newColorMode;
1965 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1966
1967 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1968 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1969 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1970 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1971 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1972 }
1973 newColorMode = pickColorMode(newDataSpace);
1974
Thierry Strudel2924d012017-08-14 15:19:37 -07001975 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001976 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001977 }
1978
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001979 mPreviousColorMatrix = colorMatrix;
1980
Dan Stoza9e56aa02015-11-02 13:00:03 -08001981 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001982 auto& displayDevice = mDisplays[displayId];
1983 if (!displayDevice->isDisplayOn()) {
1984 continue;
1985 }
1986
1987 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001988 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1989 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001990 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001991}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001992
Mathias Agopiancd60f992012-08-16 16:28:27 -07001993void SurfaceFlinger::doComposition() {
1994 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001995 ALOGV("doComposition");
1996
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001997 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001998 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001999 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002000 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002001 // transform the dirty region into this screen's coordinate space
2002 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002003
2004 // repaint the framebuffer (if needed)
2005 doDisplayComposition(hw, dirtyRegion);
2006
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007 hw->dirtyRegion.clear();
2008 hw->flip(hw->swapRegion);
2009 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07002010 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002011 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002012 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002013}
2014
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002015void SurfaceFlinger::postFramebuffer()
2016{
Mathias Agopian841cde52012-03-01 15:44:37 -08002017 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002019
Mathias Agopiana44b0412011-10-16 18:46:35 -07002020 const nsecs_t now = systemTime();
2021 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002022
Dan Stoza9e56aa02015-11-02 13:00:03 -08002023 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2024 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002025 if (!displayDevice->isDisplayOn()) {
2026 continue;
2027 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002028 const auto hwcId = displayDevice->getHwcDisplayId();
2029 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002030 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002031 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002032 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002033 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2035 sp<Fence> releaseFence = Fence::NO_FENCE;
2036 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
2037 releaseFence = displayDevice->getClientTargetAcquireFence();
2038 } else {
2039 auto hwcLayer = layer->getHwcLayer(hwcId);
2040 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002041 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002042 layer->onLayerDisplayed(releaseFence);
2043 }
2044 if (hwcId >= 0) {
2045 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002046 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002047 }
2048
Mathias Agopiana44b0412011-10-16 18:46:35 -07002049 mLastSwapBufferTime = systemTime() - now;
2050 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002051
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002052 // |mStateLock| not needed as we are on the main thread
2053 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002054 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2055 logFrameStats();
2056 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002057}
2058
Mathias Agopian87baae12012-07-31 12:38:26 -07002059void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002060{
Mathias Agopian841cde52012-03-01 15:44:37 -08002061 ATRACE_CALL();
2062
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002063 // here we keep a copy of the drawing state (that is the state that's
2064 // going to be overwritten by handleTransactionLocked()) outside of
2065 // mStateLock so that the side-effects of the State assignment
2066 // don't happen with mStateLock held (which can cause deadlocks).
2067 State drawingState(mDrawingState);
2068
Mathias Agopianca4d3602011-05-19 15:38:14 -07002069 Mutex::Autolock _l(mStateLock);
2070 const nsecs_t now = systemTime();
2071 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002072
Mathias Agopianca4d3602011-05-19 15:38:14 -07002073 // Here we're guaranteed that some transaction flags are set
2074 // so we can call handleTransactionLocked() unconditionally.
2075 // We call getTransactionFlags(), which will also clear the flags,
2076 // with mStateLock held to guarantee that mCurrentState won't change
2077 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002078
Mathias Agopiane57f2922012-08-09 16:29:12 -07002079 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002080 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002081
Mathias Agopianca4d3602011-05-19 15:38:14 -07002082 mLastTransactionTime = systemTime() - now;
2083 mDebugInTransaction = 0;
2084 invalidateHwcGeometry();
2085 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002086}
2087
Mathias Agopian87baae12012-07-31 12:38:26 -07002088void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002089{
Dan Stoza7dde5992015-05-22 09:51:44 -07002090 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002091 mCurrentState.traverseInZOrder([](Layer* layer) {
2092 layer->notifyAvailableFrames();
2093 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002094
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002095 /*
2096 * Traversal of the children
2097 * (perform the transaction for each of them if needed)
2098 */
2099
Mathias Agopian3559b072012-08-15 13:46:03 -07002100 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002101 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002102 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002103 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002104
2105 const uint32_t flags = layer->doTransaction(0);
2106 if (flags & Layer::eVisibleRegion)
2107 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002108 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002109 }
2110
2111 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002112 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002113 */
2114
Mathias Agopiane57f2922012-08-09 16:29:12 -07002115 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002116 // here we take advantage of Vector's copy-on-write semantics to
2117 // improve performance by skipping the transaction entirely when
2118 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002119 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2120 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002121 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002122 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002123 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002124 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002125
2126 // find the displays that were removed
2127 // (ie: in drawing state but not in current state)
2128 // also handle displays that changed
2129 // (ie: displays that are in both lists)
2130 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002131 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2132 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002133 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002134 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002135 // Call makeCurrent() on the primary display so we can
2136 // be sure that nothing associated with this display
2137 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002138 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002139 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002140 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002141 if (hw != NULL)
2142 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002143 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002144 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002145 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002146 } else {
2147 ALOGW("trying to remove the main display");
2148 }
2149 } else {
2150 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002151 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002152 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002153 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2154 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002155 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002156 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002157 // recreating the DisplayDevice, so we just remove it
2158 // from the drawing state, so that it get re-added
2159 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002160 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002161 if (hw != NULL)
2162 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002163 mDisplays.removeItem(display);
2164 mDrawingState.displays.removeItemsAt(i);
2165 dc--; i--;
2166 // at this point we must loop to the next item
2167 continue;
2168 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002169
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002170 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002171 if (disp != NULL) {
2172 if (state.layerStack != draw[i].layerStack) {
2173 disp->setLayerStack(state.layerStack);
2174 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002175 if ((state.orientation != draw[i].orientation)
2176 || (state.viewport != draw[i].viewport)
2177 || (state.frame != draw[i].frame))
2178 {
2179 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002180 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002181 }
Michael Lentine47e45402014-07-18 15:34:25 -07002182 if (state.width != draw[i].width || state.height != draw[i].height) {
2183 disp->setDisplaySize(state.width, state.height);
2184 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002185 }
2186 }
2187 }
2188
2189 // find displays that were added
2190 // (ie: in current state but not in drawing state)
2191 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002192 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002193 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002194
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002195 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002196 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002197 sp<IGraphicBufferProducer> bqProducer;
2198 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002199 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002200
Dan Stoza9e56aa02015-11-02 13:00:03 -08002201 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002202 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002203 // Virtual displays without a surface are dormant:
2204 // they have external state (layer stack, projection,
2205 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002206 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002207
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002208 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002209 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002210 int width = 0;
2211 int status = state.surface->query(
2212 NATIVE_WINDOW_WIDTH, &width);
2213 ALOGE_IF(status != NO_ERROR,
2214 "Unable to query width (%d)", status);
2215 int height = 0;
2216 status = state.surface->query(
2217 NATIVE_WINDOW_HEIGHT, &height);
2218 ALOGE_IF(status != NO_ERROR,
2219 "Unable to query height (%d)", status);
2220 int intFormat = 0;
2221 status = state.surface->query(
2222 NATIVE_WINDOW_FORMAT, &intFormat);
2223 ALOGE_IF(status != NO_ERROR,
2224 "Unable to query format (%d)", status);
2225 auto format = static_cast<android_pixel_format_t>(
2226 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002227
Dan Stoza8cf150a2016-08-02 10:27:31 -07002228 mHwc->allocateVirtualDisplay(width, height, &format,
2229 &hwcId);
2230 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002231
Dan Stoza5cf424b2016-05-20 14:02:39 -07002232 // TODO: Plumb requested format back up to consumer
2233
Dan Stoza9e56aa02015-11-02 13:00:03 -08002234 sp<VirtualDisplaySurface> vds =
2235 new VirtualDisplaySurface(*mHwc,
2236 hwcId, state.surface, bqProducer,
2237 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002238
2239 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002240 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002241 }
2242 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002243 ALOGE_IF(state.surface!=NULL,
2244 "adding a supported display, but rendering "
2245 "surface is provided (%p), ignoring it",
2246 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002247
2248 hwcId = state.type;
2249 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2250 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002251 }
2252
2253 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002254 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002255 sp<DisplayDevice> hw =
2256 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2257 dispSurface, producer,
2258 mRenderEngine->getEGLConfig(),
2259 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002260 hw->setLayerStack(state.layerStack);
2261 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002262 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002263 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002264 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002265 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002266 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002267 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002268 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002269 }
2270 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002271 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002272 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002273
Mathias Agopian84300952012-11-21 16:02:13 -08002274 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2275 // The transform hint might have changed for some layers
2276 // (either because a display has changed, or because a layer
2277 // as changed).
2278 //
2279 // Walk through all the layers in currentLayers,
2280 // and update their transform hint.
2281 //
2282 // If a layer is visible only on a single display, then that
2283 // display is used to calculate the hint, otherwise we use the
2284 // default display.
2285 //
2286 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2287 // the hint is set before we acquire a buffer from the surface texture.
2288 //
2289 // NOTE: layer transactions have taken place already, so we use their
2290 // drawing state. However, SurfaceFlinger's own transaction has not
2291 // happened yet, so we must use the current state layer list
2292 // (soon to become the drawing state list).
2293 //
2294 sp<const DisplayDevice> disp;
2295 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002296 bool first = true;
2297 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002298 // NOTE: we rely on the fact that layers are sorted by
2299 // layerStack first (so we don't have to traverse the list
2300 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002301 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002302 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002303 currentlayerStack = layerStack;
2304 // figure out if this layerstack is mirrored
2305 // (more than one display) if so, pick the default display,
2306 // if not, pick the only display it's on.
2307 disp.clear();
2308 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2309 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002310 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002311 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002312 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002313 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002314 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002315 break;
2316 }
2317 }
2318 }
2319 }
Chet Haase91d25932013-04-11 15:24:55 -07002320 if (disp == NULL) {
2321 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2322 // redraw after transform hint changes. See bug 8508397.
2323
2324 // could be null when this layer is using a layerStack
2325 // that is not visible on any display. Also can occur at
2326 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002327 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002328 }
Chet Haase91d25932013-04-11 15:24:55 -07002329 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002330
2331 first = false;
2332 });
Mathias Agopian84300952012-11-21 16:02:13 -08002333 }
2334
2335
Mathias Agopian3559b072012-08-15 13:46:03 -07002336 /*
2337 * Perform our own transaction if needed
2338 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002339
2340 if (mLayersAdded) {
2341 mLayersAdded = false;
2342 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002343 mVisibleRegionsDirty = true;
2344 }
2345
2346 // some layers might have been removed, so
2347 // we need to update the regions they're exposing.
2348 if (mLayersRemoved) {
2349 mLayersRemoved = false;
2350 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002351 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002352 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002353 // this layer is not visible anymore
2354 // TODO: we could traverse the tree from front to back and
2355 // compute the actual visible region
2356 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002357 Region visibleReg;
2358 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002359 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002360 }
Robert Carr2047fae2016-11-28 14:09:09 -08002361 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002362 }
2363
2364 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002365
2366 updateCursorAsync();
2367}
2368
2369void SurfaceFlinger::updateCursorAsync()
2370{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002371 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2372 auto& displayDevice = mDisplays[displayId];
2373 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002374 continue;
2375 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002376
2377 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2378 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002379 }
2380 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002381}
2382
2383void SurfaceFlinger::commitTransaction()
2384{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002385 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002386 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002387 for (const auto& l : mLayersPendingRemoval) {
2388 recordBufferingStats(l->getName().string(),
2389 l->getOccupancyHistory(true));
2390 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002391 }
2392 mLayersPendingRemoval.clear();
2393 }
2394
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002395 // If this transaction is part of a window animation then the next frame
2396 // we composite should be considered an animation as well.
2397 mAnimCompositionPending = mAnimTransactionPending;
2398
Mathias Agopian4fec8732012-06-29 14:12:52 -07002399 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002400 mDrawingState.traverseInZOrder([](Layer* layer) {
2401 layer->commitChildList();
2402 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002403 mTransactionPending = false;
2404 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002405 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002406}
2407
Chia-I Wuab0c3192017-08-01 11:29:00 -07002408void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002409 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002410{
Mathias Agopian841cde52012-03-01 15:44:37 -08002411 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002412 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002413
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002414 Region aboveOpaqueLayers;
2415 Region aboveCoveredLayers;
2416 Region dirty;
2417
Mathias Agopian87baae12012-07-31 12:38:26 -07002418 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002419
Robert Carr2047fae2016-11-28 14:09:09 -08002420 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002421 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002422 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002423
Jesse Hall01e29052013-02-19 16:13:35 -08002424 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002425 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002426 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002427
Mathias Agopianab028732010-03-16 16:41:46 -07002428 /*
2429 * opaqueRegion: area of a surface that is fully opaque.
2430 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002431 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002432
2433 /*
2434 * visibleRegion: area of a surface that is visible on screen
2435 * and not fully transparent. This is essentially the layer's
2436 * footprint minus the opaque regions above it.
2437 * Areas covered by a translucent surface are considered visible.
2438 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002440
2441 /*
2442 * coveredRegion: area of a surface that is covered by all
2443 * visible regions above it (which includes the translucent areas).
2444 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002446
Jesse Halla8026d22012-09-25 13:25:04 -07002447 /*
2448 * transparentRegion: area of a surface that is hinted to be completely
2449 * transparent. This is only used to tell when the layer has no visible
2450 * non-transparent regions and can be removed from the layer list. It
2451 * does not affect the visibleRegion of this layer or any layers
2452 * beneath it. The hint may not be correct if apps don't respect the
2453 * SurfaceView restrictions (which, sadly, some don't).
2454 */
2455 Region transparentRegion;
2456
Mathias Agopianab028732010-03-16 16:41:46 -07002457
2458 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002459 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002460 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002461 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002462 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002463 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002464 if (!visibleRegion.isEmpty()) {
2465 // Remove the transparent area from the visible region
2466 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002467 if (tr.preserveRects()) {
2468 // transform the transparent region
2469 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002470 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002471 // transformation too complex, can't do the
2472 // transparent region optimization.
2473 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002474 }
Mathias Agopianab028732010-03-16 16:41:46 -07002475 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002476
Mathias Agopianab028732010-03-16 16:41:46 -07002477 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002478 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002479 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002480 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2481 // the opaque region is the layer's footprint
2482 opaqueRegion = visibleRegion;
2483 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484 }
2485 }
2486
Mathias Agopianab028732010-03-16 16:41:46 -07002487 // Clip the covered region to the visible region
2488 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2489
2490 // Update aboveCoveredLayers for next (lower) layer
2491 aboveCoveredLayers.orSelf(visibleRegion);
2492
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002493 // subtract the opaque region covered by the layers above us
2494 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495
2496 // compute this layer's dirty region
2497 if (layer->contentDirty) {
2498 // we need to invalidate the whole region
2499 dirty = visibleRegion;
2500 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002501 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502 layer->contentDirty = false;
2503 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002504 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002505 * the exposed region consists of two components:
2506 * 1) what's VISIBLE now and was COVERED before
2507 * 2) what's EXPOSED now less what was EXPOSED before
2508 *
2509 * note that (1) is conservative, we start with the whole
2510 * visible region but only keep what used to be covered by
2511 * something -- which mean it may have been exposed.
2512 *
2513 * (2) handles areas that were not covered by anything but got
2514 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002515 */
Mathias Agopianab028732010-03-16 16:41:46 -07002516 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002517 const Region oldVisibleRegion = layer->visibleRegion;
2518 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002519 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2520 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002521 }
2522 dirty.subtractSelf(aboveOpaqueLayers);
2523
2524 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002525 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526
Mathias Agopianab028732010-03-16 16:41:46 -07002527 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002528 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002529
Jesse Halla8026d22012-09-25 13:25:04 -07002530 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002531 layer->setVisibleRegion(visibleRegion);
2532 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002533 layer->setVisibleNonTransparentRegion(
2534 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002535 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536
Mathias Agopian87baae12012-07-31 12:38:26 -07002537 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538}
2539
Chia-I Wuab0c3192017-08-01 11:29:00 -07002540void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002541 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002542 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002543 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002544 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002545 }
2546 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002547}
2548
Dan Stoza6b9454d2014-11-07 16:00:59 -08002549bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002550{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002551 ALOGV("handlePageFlip");
2552
Brian Andersond6927fb2016-07-23 23:37:30 -07002553 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554
Mathias Agopian4fec8732012-06-29 14:12:52 -07002555 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002556 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002557 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002558
2559 // Store the set of layers that need updates. This set must not change as
2560 // buffers are being latched, as this could result in a deadlock.
2561 // Example: Two producers share the same command stream and:
2562 // 1.) Layer 0 is latched
2563 // 2.) Layer 0 gets a new frame
2564 // 2.) Layer 1 gets a new frame
2565 // 3.) Layer 1 is latched.
2566 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2567 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002568 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002569 if (layer->hasQueuedFrame()) {
2570 frameQueued = true;
2571 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002572 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002573 } else {
2574 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002575 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002576 } else {
2577 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002578 }
Robert Carr2047fae2016-11-28 14:09:09 -08002579 });
2580
Dan Stoza9e56aa02015-11-02 13:00:03 -08002581 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002582 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002583 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002584 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002585 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002586 newDataLatched = true;
2587 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002588 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002589
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002590 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002591
2592 // If we will need to wake up at some time in the future to deal with a
2593 // queued frame that shouldn't be displayed during this vsync period, wake
2594 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002595 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002596 signalLayerUpdate();
2597 }
2598
2599 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002600 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601}
2602
Mathias Agopianad456f92011-01-13 17:53:01 -08002603void SurfaceFlinger::invalidateHwcGeometry()
2604{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002606}
2607
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002608
Fabien Sanglard830b8472016-11-30 16:35:58 -08002609void SurfaceFlinger::doDisplayComposition(
2610 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002611 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612{
Dan Stoza71433162014-02-04 16:22:36 -08002613 // We only need to actually compose the display if:
2614 // 1) It is being handled by hardware composer, which may need this to
2615 // keep its virtual display state machine in sync, or
2616 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002617 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002618 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002619 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002620 return;
2621 }
2622
Dan Stoza9e56aa02015-11-02 13:00:03 -08002623 ALOGV("doDisplayComposition");
2624
Mathias Agopian87baae12012-07-31 12:38:26 -07002625 Region dirtyRegion(inDirtyRegion);
2626
Mathias Agopianb8a55602009-06-26 19:06:36 -07002627 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002628 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002629
Fabien Sanglard830b8472016-11-30 16:35:58 -08002630 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002631 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002632 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2633 // takes a rectangle, we must make sure to update that whole
2634 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002635 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002636 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002637 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002638 // We need to redraw the rectangle that will be updated
2639 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002640 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002641 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002642 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002643 } else {
2644 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002645 dirtyRegion.set(displayDevice->bounds());
2646 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647 }
2648 }
2649
Fabien Sanglard830b8472016-11-30 16:35:58 -08002650 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002652 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002653 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002654
2655 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002656 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657}
2658
Dan Stoza9e56aa02015-11-02 13:00:03 -08002659bool SurfaceFlinger::doComposeSurfaces(
2660 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002661{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002662 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002663
Dan Stoza9e56aa02015-11-02 13:00:03 -08002664 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002665
2666 mat4 oldColorMatrix;
2667 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2668 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2669 if (applyColorMatrix) {
2670 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2671 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2672 }
2673
Dan Stoza9e56aa02015-11-02 13:00:03 -08002674 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2675 if (hasClientComposition) {
2676 ALOGV("hasClientComposition");
2677
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002678#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01002679 mRenderEngine->setWideColor(
2680 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2681 mRenderEngine->setColorMode(mForceNativeColorMode ?
2682 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002683#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002684 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002685 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002686 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002687 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002688
2689 // |mStateLock| not needed as we are on the main thread
2690 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002691 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2692 }
2693 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002694 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002695
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002696 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002697 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2698 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002699 // when using overlays, we assume a fully transparent framebuffer
2700 // NOTE: we could reduce how much we need to clear, for instance
2701 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002702 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002703 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002704 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002705 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002706 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002707 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002708
2709 // we remove the scissor part
2710 // we're left with the letterbox region
2711 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002712 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002713
2714 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002715 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002716
2717 // but limit it to the dirty region
2718 region.andSelf(dirty);
2719
Mathias Agopianb9494d52012-04-18 02:28:45 -07002720 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002721 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002722 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002723 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002724 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002725 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002726
Dan Stoza9e56aa02015-11-02 13:00:03 -08002727 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002728 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002729 // scissor on the main display. It should never be needed
2730 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002731 const Rect& bounds(displayDevice->getBounds());
2732 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002733 if (scissor != bounds) {
2734 // scissor doesn't match the screen's dimensions, so we
2735 // need to clear everything outside of it and enable
2736 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002737
Mathias Agopianf45c5102012-10-24 16:29:17 -07002738 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002739 const uint32_t height = displayDevice->getHeight();
2740 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002741 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002742 }
2743 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002744 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002745
Mathias Agopian85d751c2012-08-29 16:59:24 -07002746 /*
2747 * and then, render the layers targeted at the framebuffer
2748 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002749
Dan Stoza9e56aa02015-11-02 13:00:03 -08002750 ALOGV("Rendering client layers");
2751 const Transform& displayTransform = displayDevice->getTransform();
2752 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002753 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002754 bool firstLayer = true;
2755 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2756 const Region clip(dirty.intersect(
2757 displayTransform.transform(layer->visibleRegion)));
2758 ALOGV("Layer: %s", layer->getName().string());
2759 ALOGV(" Composition type: %s",
2760 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002761 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002762 switch (layer->getCompositionType(hwcId)) {
2763 case HWC2::Composition::Cursor:
2764 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002765 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002766 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002767 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002768 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2769 layer->isOpaque(state) && (state.alpha == 1.0f)
2770 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002771 // never clear the very first layer since we're
2772 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002773 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002774 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002775 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002776 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002777 case HWC2::Composition::Client: {
2778 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002779 break;
2780 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002781 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002782 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002783 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002784 } else {
2785 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002786 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002787 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002788 }
2789 } else {
2790 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002791 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002792 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002793 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002794 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002795 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002796 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002797 }
2798 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002799
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002800 if (applyColorMatrix) {
2801 getRenderEngine().setupColorTransform(oldColorMatrix);
2802 }
2803
Mathias Agopianf45c5102012-10-24 16:29:17 -07002804 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002805 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002806 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807}
2808
Fabien Sanglard830b8472016-11-30 16:35:58 -08002809void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2810 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002811 RenderEngine& engine(getRenderEngine());
2812 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813}
2814
Dan Stoza7d89d062015-04-30 13:29:25 -07002815status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002816 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002817 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002818 const sp<Layer>& lbc,
2819 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002820{
Dan Stoza7d89d062015-04-30 13:29:25 -07002821 // add this layer to the current state list
2822 {
2823 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002824 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002825 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2826 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002827 return NO_MEMORY;
2828 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002829 if (parent == nullptr) {
2830 mCurrentState.layersSortedByZ.add(lbc);
2831 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002832 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2833 ALOGE("addClientLayer called with a removed parent");
2834 return NAME_NOT_FOUND;
2835 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002836 parent->addChild(lbc);
2837 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002838
Dan Stoza7d89d062015-04-30 13:29:25 -07002839 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002840 mLayersAdded = true;
2841 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002842 }
2843
Mathias Agopian96f08192010-06-02 23:28:45 -07002844 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002845 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002846
Dan Stoza7d89d062015-04-30 13:29:25 -07002847 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002848}
2849
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002850status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002851 Mutex::Autolock _l(mStateLock);
2852
Robert Carr1f0a16a2016-10-24 16:27:39 -07002853 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002854 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002855 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002856 if (topLevelOnly) {
2857 return NO_ERROR;
2858 }
2859
Chia-I Wu98f1c102017-05-30 14:54:08 -07002860 sp<Layer> ancestor = p;
2861 while (ancestor->getParent() != nullptr) {
2862 ancestor = ancestor->getParent();
2863 }
2864 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2865 ALOGE("removeLayer called with a layer whose parent has been removed");
2866 return NAME_NOT_FOUND;
2867 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002868
2869 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002870 } else {
2871 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002872 }
2873
Robert Carr136e2f62017-02-08 17:54:29 -08002874 // As a matter of normal operation, the LayerCleaner will produce a second
2875 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2876 // so we will succeed in promoting it, but it's already been removed
2877 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2878 // otherwise something has gone wrong and we are leaking the layer.
2879 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002880 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2881 layer->getName().string(),
2882 (p != nullptr) ? p->getName().string() : "no-parent");
2883 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002884 } else if (index < 0) {
2885 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002886 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002887
Chia-I Wuc6657022017-08-15 11:18:17 -07002888 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002889 mLayersPendingRemoval.add(layer);
2890 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002891 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002892 setTransactionFlags(eTransactionNeeded);
2893 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894}
2895
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002896uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002897 return android_atomic_release_load(&mTransactionFlags);
2898}
2899
Mathias Agopian3f844832013-08-07 21:24:32 -07002900uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002901 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2902}
2903
Mathias Agopian3f844832013-08-07 21:24:32 -07002904uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2906 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002907 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908 }
2909 return old;
2910}
2911
Mathias Agopian8b33f032012-07-24 20:43:54 -07002912void SurfaceFlinger::setTransactionState(
2913 const Vector<ComposerState>& state,
2914 const Vector<DisplayState>& displays,
2915 uint32_t flags)
2916{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002917 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002918 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002919 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002920
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002921 if (flags & eAnimation) {
2922 // For window updates that are part of an animation we must wait for
2923 // previous animation "frames" to be handled.
2924 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002925 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002926 if (CC_UNLIKELY(err != NO_ERROR)) {
2927 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002928 // caller after a few seconds.
2929 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2930 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002931 mAnimTransactionPending = false;
2932 break;
2933 }
2934 }
2935 }
2936
Mathias Agopiane57f2922012-08-09 16:29:12 -07002937 size_t count = displays.size();
2938 for (size_t i=0 ; i<count ; i++) {
2939 const DisplayState& s(displays[i]);
2940 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002941 }
2942
Mathias Agopiane57f2922012-08-09 16:29:12 -07002943 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002944 for (size_t i=0 ; i<count ; i++) {
2945 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002946 // Here we need to check that the interface we're given is indeed
2947 // one of our own. A malicious client could give us a NULL
2948 // IInterface, or one of its own or even one of our own but a
2949 // different type. All these situations would cause us to crash.
2950 //
2951 // NOTE: it would be better to use RTTI as we could directly check
2952 // that we have a Client*. however, RTTI is disabled in Android.
2953 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002954 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002955 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002956 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002957 sp<Client> client( static_cast<Client *>(s.client.get()) );
2958 transactionFlags |= setClientStateLocked(client, s.state);
2959 }
2960 }
2961 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002962 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002963
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002964 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2965 // anyway. This can be used as a flush mechanism for previous async transactions.
2966 // Empty animation transaction can be used to simulate back-pressure, so also force a
2967 // transaction for empty animation transactions.
2968 if (transactionFlags == 0 &&
2969 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002970 transactionFlags = eTransactionNeeded;
2971 }
2972
Mathias Agopian386aa982011-11-07 21:58:03 -08002973 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002974 if (mInterceptor.isEnabled()) {
2975 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2976 }
Irvel468051e2016-06-13 16:44:44 -07002977
Mathias Agopian386aa982011-11-07 21:58:03 -08002978 // this triggers the transaction
2979 setTransactionFlags(transactionFlags);
2980
2981 // if this is a synchronous transaction, wait for it to take effect
2982 // before returning.
2983 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002984 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002985 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002986 if (flags & eAnimation) {
2987 mAnimTransactionPending = true;
2988 }
2989 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002990 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2991 if (CC_UNLIKELY(err != NO_ERROR)) {
2992 // just in case something goes wrong in SF, return to the
2993 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002994 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2995 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002996 break;
2997 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002998 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002999 }
3000}
3001
Mathias Agopiane57f2922012-08-09 16:29:12 -07003002uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3003{
Jesse Hall9a143922012-10-04 16:29:19 -07003004 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3005 if (dpyIdx < 0)
3006 return 0;
3007
Mathias Agopiane57f2922012-08-09 16:29:12 -07003008 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003009 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003010 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003011 const uint32_t what = s.what;
3012 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003013 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003014 disp.surface = s.surface;
3015 flags |= eDisplayTransactionNeeded;
3016 }
3017 }
3018 if (what & DisplayState::eLayerStackChanged) {
3019 if (disp.layerStack != s.layerStack) {
3020 disp.layerStack = s.layerStack;
3021 flags |= eDisplayTransactionNeeded;
3022 }
3023 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003024 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003025 if (disp.orientation != s.orientation) {
3026 disp.orientation = s.orientation;
3027 flags |= eDisplayTransactionNeeded;
3028 }
3029 if (disp.frame != s.frame) {
3030 disp.frame = s.frame;
3031 flags |= eDisplayTransactionNeeded;
3032 }
3033 if (disp.viewport != s.viewport) {
3034 disp.viewport = s.viewport;
3035 flags |= eDisplayTransactionNeeded;
3036 }
3037 }
Michael Lentine47e45402014-07-18 15:34:25 -07003038 if (what & DisplayState::eDisplaySizeChanged) {
3039 if (disp.width != s.width) {
3040 disp.width = s.width;
3041 flags |= eDisplayTransactionNeeded;
3042 }
3043 if (disp.height != s.height) {
3044 disp.height = s.height;
3045 flags |= eDisplayTransactionNeeded;
3046 }
3047 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003048 }
3049 return flags;
3050}
3051
3052uint32_t SurfaceFlinger::setClientStateLocked(
3053 const sp<Client>& client,
3054 const layer_state_t& s)
3055{
3056 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003057 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003058 if (layer != 0) {
3059 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003060 bool geometryAppliesWithResize =
3061 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003062 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003063 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003064 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003065 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003066 }
3067 if (what & layer_state_t::eLayerChanged) {
3068 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069 const auto& p = layer->getParent();
3070 if (p == nullptr) {
3071 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3072 if (layer->setLayer(s.z) && idx >= 0) {
3073 mCurrentState.layersSortedByZ.removeAt(idx);
3074 mCurrentState.layersSortedByZ.add(layer);
3075 // we need traversal (state changed)
3076 // AND transaction (list changed)
3077 flags |= eTransactionNeeded|eTraversalNeeded;
3078 }
3079 } else {
3080 if (p->setChildLayer(layer, s.z)) {
3081 flags |= eTransactionNeeded|eTraversalNeeded;
3082 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003083 }
3084 }
Robert Carrdb66e622017-04-10 16:55:57 -07003085 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003086 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003087 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003088 mCurrentState.layersSortedByZ.removeAt(idx);
3089 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003090 flags |= eTransactionNeeded|eTraversalNeeded;
3091 }
3092 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003093 if (what & layer_state_t::eSizeChanged) {
3094 if (layer->setSize(s.w, s.h)) {
3095 flags |= eTraversalNeeded;
3096 }
3097 }
3098 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003099 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003100 flags |= eTraversalNeeded;
3101 }
3102 if (what & layer_state_t::eMatrixChanged) {
3103 if (layer->setMatrix(s.matrix))
3104 flags |= eTraversalNeeded;
3105 }
3106 if (what & layer_state_t::eTransparentRegionChanged) {
3107 if (layer->setTransparentRegionHint(s.transparentRegion))
3108 flags |= eTraversalNeeded;
3109 }
Dan Stoza23116082015-06-18 14:58:39 -07003110 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003111 if (layer->setFlags(s.flags, s.mask))
3112 flags |= eTraversalNeeded;
3113 }
3114 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003115 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003116 flags |= eTraversalNeeded;
3117 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003118 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003119 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003120 flags |= eTraversalNeeded;
3121 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003122 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003123 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003124 // We only allow setting layer stacks for top level layers,
3125 // everything else inherits layer stack from its parent.
3126 if (layer->hasParent()) {
3127 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3128 layer->getName().string());
3129 } else if (idx < 0) {
3130 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3131 "that also does not appear in the top level layer list. Something"
3132 " has gone wrong.", layer->getName().string());
3133 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003134 mCurrentState.layersSortedByZ.removeAt(idx);
3135 mCurrentState.layersSortedByZ.add(layer);
3136 // we need traversal (state changed)
3137 // AND transaction (list changed)
3138 flags |= eTransactionNeeded|eTraversalNeeded;
3139 }
3140 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003141 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003142 if (s.barrierHandle != nullptr) {
3143 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3144 } else if (s.barrierGbp != nullptr) {
3145 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3146 if (authenticateSurfaceTextureLocked(gbp)) {
3147 const auto& otherLayer =
3148 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3149 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3150 } else {
3151 ALOGE("Attempt to defer transaction to to an"
3152 " unrecognized GraphicBufferProducer");
3153 }
3154 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003155 // We don't trigger a traversal here because if no other state is
3156 // changed, we don't want this to cause any more work
3157 }
Robert Carr1db73f62016-12-21 12:58:51 -08003158 if (what & layer_state_t::eReparentChildren) {
3159 if (layer->reparentChildren(s.reparentHandle)) {
3160 flags |= eTransactionNeeded|eTraversalNeeded;
3161 }
3162 }
Robert Carr9524cb32017-02-13 11:32:32 -08003163 if (what & layer_state_t::eDetachChildren) {
3164 layer->detachChildren();
3165 }
Robert Carrc3574f72016-03-24 12:19:32 -07003166 if (what & layer_state_t::eOverrideScalingModeChanged) {
3167 layer->setOverrideScalingMode(s.overrideScalingMode);
3168 // We don't trigger a traversal here because if no other state is
3169 // changed, we don't want this to cause any more work
3170 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003171 }
3172 return flags;
3173}
3174
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003175status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003176 const String8& name,
3177 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003178 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003179 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3180 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003181{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003182 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003183 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003184 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003185 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003186 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003187
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003188 status_t result = NO_ERROR;
3189
3190 sp<Layer> layer;
3191
Cody Northropbc755282017-03-31 12:00:08 -06003192 String8 uniqueName = getUniqueLayerName(name);
3193
Mathias Agopian3165cc22012-08-08 19:42:09 -07003194 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3195 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003196 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003197 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003198 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003199 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003200 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003201 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003202 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003203 handle, gbp, &layer);
3204 break;
3205 default:
3206 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207 break;
3208 }
3209
Dan Stoza7d89d062015-04-30 13:29:25 -07003210 if (result != NO_ERROR) {
3211 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003213
Chia-I Wuab0c3192017-08-01 11:29:00 -07003214 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3215 // TODO b/64227542
3216 if (windowType == 441731) {
3217 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3218 layer->setPrimaryDisplayOnly();
3219 }
3220
Albert Chaulk479c60c2017-01-27 14:21:34 -05003221 layer->setInfo(windowType, ownerUid);
3222
Robert Carr1f0a16a2016-10-24 16:27:39 -07003223 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003224 if (result != NO_ERROR) {
3225 return result;
3226 }
Irvelffc9efc2016-07-27 15:16:37 -07003227 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003228
3229 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003230 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003231}
3232
Cody Northropbc755282017-03-31 12:00:08 -06003233String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3234{
3235 bool matchFound = true;
3236 uint32_t dupeCounter = 0;
3237
3238 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3239 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3240
3241 // Loop over layers until we're sure there is no matching name
3242 while (matchFound) {
3243 matchFound = false;
3244 mDrawingState.traverseInZOrder([&](Layer* layer) {
3245 if (layer->getName() == uniqueName) {
3246 matchFound = true;
3247 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3248 }
3249 });
3250 }
3251
3252 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3253
3254 return uniqueName;
3255}
3256
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003257status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3258 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3259 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003260{
3261 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003262 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263 case PIXEL_FORMAT_TRANSPARENT:
3264 case PIXEL_FORMAT_TRANSLUCENT:
3265 format = PIXEL_FORMAT_RGBA_8888;
3266 break;
3267 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003268 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003269 break;
3270 }
3271
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003272 *outLayer = new Layer(this, client, name, w, h, flags);
3273 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3274 if (err == NO_ERROR) {
3275 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003276 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003278
3279 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3280 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003281}
3282
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003283status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3284 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3285 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003287 *outLayer = new LayerDim(this, client, name, w, h, flags);
3288 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003289 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003290 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003291}
3292
Mathias Agopianac9fa422013-02-11 16:40:36 -08003293status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003294{
Robert Carr9524cb32017-02-13 11:32:32 -08003295 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003296 status_t err = NO_ERROR;
3297 sp<Layer> l(client->getLayerUser(handle));
3298 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003299 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003300 err = removeLayer(l);
3301 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3302 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003303 }
3304 return err;
3305}
3306
Mathias Agopian13127d82013-03-05 17:47:11 -08003307status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003308{
Mathias Agopian67106042013-03-14 19:18:13 -07003309 // called by ~LayerCleaner() when all references to the IBinder (handle)
3310 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003311 sp<Layer> l = layer.promote();
3312 if (l == nullptr) {
3313 // The layer has already been removed, carry on
3314 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003315 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003316 // If we have a parent, then we can continue to live as long as it does.
3317 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003318}
3319
Mathias Agopianb60314a2012-04-10 22:09:54 -07003320// ---------------------------------------------------------------------------
3321
Andy McFadden13a082e2012-08-24 10:16:42 -07003322void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003323 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003324 Vector<ComposerState> state;
3325 Vector<DisplayState> displays;
3326 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003327 d.what = DisplayState::eDisplayProjectionChanged |
3328 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003329 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003330 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003331 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003332 d.frame.makeInvalid();
3333 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003334 d.width = 0;
3335 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003336 displays.add(d);
3337 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003338 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3339 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003340
Dan Stoza9e56aa02015-11-02 13:00:03 -08003341 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3342 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003343 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003344
Brian Andersond0010582017-03-07 13:20:31 -08003345 // Use phase of 0 since phase is not known.
3346 // Use latency of 0, which will snap to the ideal latency.
3347 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003348}
3349
3350void SurfaceFlinger::initializeDisplays() {
3351 class MessageScreenInitialized : public MessageBase {
3352 SurfaceFlinger* flinger;
3353 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003354 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003355 virtual bool handler() {
3356 flinger->onInitializeDisplays();
3357 return true;
3358 }
3359 };
3360 sp<MessageBase> msg = new MessageScreenInitialized(this);
3361 postMessageAsync(msg); // we may be called from main thread, use async message
3362}
3363
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003364void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003365 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003366 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3367 this);
3368 int32_t type = hw->getDisplayType();
3369 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003370
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003371 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003372 return;
3373 }
3374
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003375 hw->setPowerMode(mode);
3376 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3377 ALOGW("Trying to set power mode for virtual display");
3378 return;
3379 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003380
Irvelffc9efc2016-07-27 15:16:37 -07003381 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003382 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003383 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3384 if (idx < 0) {
3385 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3386 return;
3387 }
3388 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3389 }
3390
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003391 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003392 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003393 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003394 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3395 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003396 // FIXME: eventthread only knows about the main display right now
3397 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003398 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003399 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003400
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003401 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003402 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003403 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003404
3405 struct sched_param param = {0};
3406 param.sched_priority = 1;
3407 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3408 ALOGW("Couldn't set SCHED_FIFO on display on");
3409 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003410 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003411 // Turn off the display
3412 struct sched_param param = {0};
3413 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3414 ALOGW("Couldn't set SCHED_OTHER on display off");
3415 }
3416
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003417 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003418 disableHardwareVsync(true); // also cancels any in-progress resync
3419
Mathias Agopiancde87a32012-09-13 14:09:01 -07003420 // FIXME: eventthread only knows about the main display right now
3421 mEventThread->onScreenReleased();
3422 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003423
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003424 getHwComposer().setPowerMode(type, mode);
3425 mVisibleRegionsDirty = true;
3426 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003427 } else if (mode == HWC_POWER_MODE_DOZE ||
3428 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003429 // Update display while dozing
3430 getHwComposer().setPowerMode(type, mode);
3431 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3432 // FIXME: eventthread only knows about the main display right now
3433 mEventThread->onScreenAcquired();
3434 resyncToHardwareVsync(true);
3435 }
3436 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3437 // Leave display going to doze
3438 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3439 disableHardwareVsync(true); // also cancels any in-progress resync
3440 // FIXME: eventthread only knows about the main display right now
3441 mEventThread->onScreenReleased();
3442 }
3443 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003444 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003445 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003446 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003447 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003448}
3449
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003450void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3451 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003452 SurfaceFlinger& mFlinger;
3453 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003454 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003455 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003456 MessageSetPowerMode(SurfaceFlinger& flinger,
3457 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3458 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003459 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003460 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003461 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003462 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003463 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003464 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003465 ALOGW("Attempt to set power mode = %d for virtual display",
3466 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003467 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003468 mFlinger.setPowerModeInternal(
3469 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003470 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003471 return true;
3472 }
3473 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003474 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003475 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003476}
3477
3478// ---------------------------------------------------------------------------
3479
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003480status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3481{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003482 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003483
Mathias Agopianbd115332013-04-18 16:41:04 -07003484 IPCThreadState* ipc = IPCThreadState::self();
3485 const int pid = ipc->getCallingPid();
3486 const int uid = ipc->getCallingUid();
3487 if ((uid != AID_SHELL) &&
3488 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003489 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003490 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003491 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003492 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003493 // (this would indicate SF is stuck, but we want to be able to
3494 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003495 status_t err = mStateLock.timedLock(s2ns(1));
3496 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003497 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003498 result.appendFormat(
3499 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3500 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003501 }
3502
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003503 bool dumpAll = true;
3504 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003505 size_t numArgs = args.size();
3506 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003507 if ((index < numArgs) &&
3508 (args[index] == String16("--list"))) {
3509 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003510 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003511 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003512 }
3513
3514 if ((index < numArgs) &&
3515 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003516 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003517 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003518 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003519 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003520
3521 if ((index < numArgs) &&
3522 (args[index] == String16("--latency-clear"))) {
3523 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003524 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003525 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003526 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003527
3528 if ((index < numArgs) &&
3529 (args[index] == String16("--dispsync"))) {
3530 index++;
3531 mPrimaryDispSync.dump(result);
3532 dumpAll = false;
3533 }
Dan Stozab90cf072015-03-05 11:05:59 -08003534
3535 if ((index < numArgs) &&
3536 (args[index] == String16("--static-screen"))) {
3537 index++;
3538 dumpStaticScreenStats(result);
3539 dumpAll = false;
3540 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003541
3542 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003543 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003544 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003545 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003546 dumpAll = false;
3547 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003548
3549 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3550 index++;
3551 dumpWideColorInfo(result);
3552 dumpAll = false;
3553 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003554 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003555
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003556 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003557 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003558 }
3559
Mathias Agopian9795c422009-08-26 16:36:26 -07003560 if (locked) {
3561 mStateLock.unlock();
3562 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003563 }
3564 write(fd, result.string(), result.size());
3565 return NO_ERROR;
3566}
3567
Dan Stozac7014012014-02-14 15:03:43 -08003568void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3569 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003570{
Robert Carr2047fae2016-11-28 14:09:09 -08003571 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003572 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003573 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003574}
3575
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003576void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003577 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003578{
3579 String8 name;
3580 if (index < args.size()) {
3581 name = String8(args[index]);
3582 index++;
3583 }
3584
Dan Stoza9e56aa02015-11-02 13:00:03 -08003585 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3586 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003587 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003588
3589 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003590 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003591 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003592 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003593 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003594 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003595 }
Robert Carr2047fae2016-11-28 14:09:09 -08003596 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003597 }
3598}
3599
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003600void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003601 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003602{
3603 String8 name;
3604 if (index < args.size()) {
3605 name = String8(args[index]);
3606 index++;
3607 }
3608
Robert Carr2047fae2016-11-28 14:09:09 -08003609 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003610 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003611 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003612 }
Robert Carr2047fae2016-11-28 14:09:09 -08003613 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003614
Svetoslavd85084b2014-03-20 10:28:31 -07003615 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003616}
3617
Jamie Gennis6547ff42013-07-16 20:12:42 -07003618// This should only be called from the main thread. Otherwise it would need
3619// the lock and should use mCurrentState rather than mDrawingState.
3620void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003621 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003622 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003623 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003624
3625 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3626}
3627
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003628void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003629{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003630 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003631 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3632
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003633 if (isLayerTripleBufferingDisabled())
3634 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003635
3636 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003637 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003638 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003639 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003640 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3641 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003642 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003643}
3644
Dan Stozab90cf072015-03-05 11:05:59 -08003645void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3646{
3647 result.appendFormat("Static screen stats:\n");
3648 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3649 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3650 float percent = 100.0f *
3651 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3652 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3653 b + 1, bucketTimeSec, percent);
3654 }
3655 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3656 float percent = 100.0f *
3657 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3658 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3659 NUM_BUCKETS - 1, bucketTimeSec, percent);
3660}
3661
Dan Stozae77c7662016-05-13 11:37:28 -07003662void SurfaceFlinger::recordBufferingStats(const char* layerName,
3663 std::vector<OccupancyTracker::Segment>&& history) {
3664 Mutex::Autolock lock(mBufferingStatsMutex);
3665 auto& stats = mBufferingStats[layerName];
3666 for (const auto& segment : history) {
3667 if (!segment.usedThirdBuffer) {
3668 stats.twoBufferTime += segment.totalTime;
3669 }
3670 if (segment.occupancyAverage < 1.0f) {
3671 stats.doubleBufferedTime += segment.totalTime;
3672 } else if (segment.occupancyAverage < 2.0f) {
3673 stats.tripleBufferedTime += segment.totalTime;
3674 }
3675 ++stats.numSegments;
3676 stats.totalTime += segment.totalTime;
3677 }
3678}
3679
Brian Andersond6927fb2016-07-23 23:37:30 -07003680void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3681 result.appendFormat("Layer frame timestamps:\n");
3682
3683 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3684 const size_t count = currentLayers.size();
3685 for (size_t i=0 ; i<count ; i++) {
3686 currentLayers[i]->dumpFrameEvents(result);
3687 }
3688}
3689
Dan Stozae77c7662016-05-13 11:37:28 -07003690void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3691 result.append("Buffering stats:\n");
3692 result.append(" [Layer name] <Active time> <Two buffer> "
3693 "<Double buffered> <Triple buffered>\n");
3694 Mutex::Autolock lock(mBufferingStatsMutex);
3695 typedef std::tuple<std::string, float, float, float> BufferTuple;
3696 std::map<float, BufferTuple, std::greater<float>> sorted;
3697 for (const auto& statsPair : mBufferingStats) {
3698 const char* name = statsPair.first.c_str();
3699 const BufferingStats& stats = statsPair.second;
3700 if (stats.numSegments == 0) {
3701 continue;
3702 }
3703 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3704 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3705 stats.totalTime;
3706 float doubleBufferRatio = static_cast<float>(
3707 stats.doubleBufferedTime) / stats.totalTime;
3708 float tripleBufferRatio = static_cast<float>(
3709 stats.tripleBufferedTime) / stats.totalTime;
3710 sorted.insert({activeTime, {name, twoBufferRatio,
3711 doubleBufferRatio, tripleBufferRatio}});
3712 }
3713 for (const auto& sortedPair : sorted) {
3714 float activeTime = sortedPair.first;
3715 const BufferTuple& values = sortedPair.second;
3716 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3717 std::get<0>(values).c_str(), activeTime,
3718 std::get<1>(values), std::get<2>(values),
3719 std::get<3>(values));
3720 }
3721 result.append("\n");
3722}
3723
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003724void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3725 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003726 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003727
3728 // TODO: print out if wide-color mode is active or not
3729
3730 for (size_t d = 0; d < mDisplays.size(); d++) {
3731 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3732 int32_t hwcId = displayDevice->getHwcDisplayId();
3733 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3734 continue;
3735 }
3736
3737 result.appendFormat("Display %d color modes:\n", hwcId);
3738 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3739 for (auto&& mode : modes) {
3740 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3741 }
3742
3743 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3744 result.appendFormat(" Current color mode: %s (%d)\n",
3745 decodeColorMode(currentMode).c_str(), currentMode);
3746 }
3747 result.append("\n");
3748}
3749
Mathias Agopian74d211a2013-04-22 16:55:35 +02003750void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3751 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003752{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003753 bool colorize = false;
3754 if (index < args.size()
3755 && (args[index] == String16("--color"))) {
3756 colorize = true;
3757 index++;
3758 }
3759
3760 Colorizer colorizer(colorize);
3761
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003762 // figure out if we're stuck somewhere
3763 const nsecs_t now = systemTime();
3764 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3765 const nsecs_t inTransaction(mDebugInTransaction);
3766 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3767 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3768
3769 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003770 * Dump library configuration.
3771 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003772
3773 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003774 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003775 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003776 appendSfConfigString(result);
3777 appendUiConfigString(result);
3778 appendGuiConfigString(result);
3779 result.append("\n");
3780
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003781 result.append("\nWide-Color information:\n");
3782 dumpWideColorInfo(result);
3783
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003784 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003785 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003786 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003787 result.append(SyncFeatures::getInstance().toString());
3788 result.append("\n");
3789
Dan Stoza9e56aa02015-11-02 13:00:03 -08003790 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3791
Andy McFadden41d67d72014-04-25 16:58:34 -07003792 colorizer.bold(result);
3793 result.append("DispSync configuration: ");
3794 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003795 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003796 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003797 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003798 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003799 result.append("\n");
3800
Dan Stozab90cf072015-03-05 11:05:59 -08003801 // Dump static screen stats
3802 result.append("\n");
3803 dumpStaticScreenStats(result);
3804 result.append("\n");
3805
Dan Stozae77c7662016-05-13 11:37:28 -07003806 dumpBufferingStats(result);
3807
Andy McFadden4803b742012-09-24 19:07:20 -07003808 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003809 * Dump the visible layer list
3810 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003811 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003812 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003813 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003814 mCurrentState.traverseInZOrder([&](Layer* layer) {
Kalle Raitaa099a242017-01-11 11:17:29 -08003815 result.append(to_string(layer->getLayerDebugInfo()).c_str());
Robert Carr2047fae2016-11-28 14:09:09 -08003816 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003817
3818 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003819 * Dump Display state
3820 */
3821
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003822 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003823 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003824 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003825 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3826 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003827 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003828 }
3829
3830 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003831 * Dump SurfaceFlinger global state
3832 */
3833
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003834 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003835 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003836 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003837
Mathias Agopian888c8222012-08-04 21:10:38 -07003838 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003839 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003840
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003841 colorizer.bold(result);
3842 result.appendFormat("EGL implementation : %s\n",
3843 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3844 colorizer.reset(result);
3845 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003846 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003847
Mathias Agopian875d8e12013-06-07 15:35:48 -07003848 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003849
Mathias Agopian42977342012-08-05 00:40:46 -07003850 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003851 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3852 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003853 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003854 " last eglSwapBuffers() time: %f us\n"
3855 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003856 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003857 " refresh-rate : %f fps\n"
3858 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003859 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003860 " gpu_to_cpu_unsupported : %d\n"
3861 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003862 mLastSwapBufferTime/1000.0,
3863 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003864 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003865 1e9 / activeConfig->getVsyncPeriod(),
3866 activeConfig->getDpiX(),
3867 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003868 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003869
Mathias Agopian74d211a2013-04-22 16:55:35 +02003870 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003871 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003872
Mathias Agopian74d211a2013-04-22 16:55:35 +02003873 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003874 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003875
3876 /*
3877 * VSYNC state
3878 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003879 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003880 result.append("\n");
3881
3882 /*
3883 * HWC layer minidump
3884 */
3885 for (size_t d = 0; d < mDisplays.size(); d++) {
3886 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3887 int32_t hwcId = displayDevice->getHwcDisplayId();
3888 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3889 continue;
3890 }
3891
3892 result.appendFormat("Display %d HWC layers:\n", hwcId);
3893 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003894 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003895 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003896 });
Dan Stozae22aec72016-08-01 13:20:59 -07003897 result.append("\n");
3898 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003899
3900 /*
3901 * Dump HWComposer state
3902 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003903 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003904 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003905 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003906 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003907 result.appendFormat(" h/w composer %s\n",
3908 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003909 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003910
3911 /*
3912 * Dump gralloc state
3913 */
3914 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3915 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003916
3917 /*
3918 * Dump VrFlinger state if in use.
3919 */
3920 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3921 result.append("VrFlinger state:\n");
3922 result.append(mVrFlinger->Dump().c_str());
3923 result.append("\n");
3924 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003925}
3926
Mathias Agopian13127d82013-03-05 17:47:11 -08003927const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003928SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003929 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003930 wp<IBinder> dpy;
3931 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3932 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3933 dpy = mDisplays.keyAt(i);
3934 break;
3935 }
3936 }
3937 if (dpy == NULL) {
3938 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3939 // Just use the primary display so we have something to return
3940 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3941 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003942 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003943}
3944
Keun young Park63f165f2012-08-31 10:53:36 -07003945bool SurfaceFlinger::startDdmConnection()
3946{
3947 void* libddmconnection_dso =
3948 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3949 if (!libddmconnection_dso) {
3950 return false;
3951 }
3952 void (*DdmConnection_start)(const char* name);
3953 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003954 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003955 if (!DdmConnection_start) {
3956 dlclose(libddmconnection_dso);
3957 return false;
3958 }
3959 (*DdmConnection_start)(getServiceName());
3960 return true;
3961}
3962
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003963status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003964 switch (code) {
3965 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003966 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003967 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003968 case CLEAR_ANIMATION_FRAME_STATS:
3969 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003970 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003971 case GET_HDR_CAPABILITIES:
Chia-I Wu6200eac2017-10-05 14:24:41 -07003972 case ENABLE_VSYNC_INJECTIONS:
3973 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003974 {
3975 // codes that require permission check
3976 IPCThreadState* ipc = IPCThreadState::self();
3977 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003978 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003979 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003980 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003981 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003982 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003983 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003984 break;
3985 }
Robert Carr1db73f62016-12-21 12:58:51 -08003986 /*
3987 * Calling setTransactionState is safe, because you need to have been
3988 * granted a reference to Client* and Handle* to do anything with it.
3989 *
3990 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3991 */
3992 case SET_TRANSACTION_STATE:
3993 case CREATE_SCOPED_CONNECTION:
3994 {
3995 return OK;
3996 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003997 case CAPTURE_SCREEN:
3998 {
3999 // codes that require permission check
4000 IPCThreadState* ipc = IPCThreadState::self();
4001 const int pid = ipc->getCallingPid();
4002 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004003 if ((uid != AID_GRAPHICS) &&
4004 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004005 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004006 return PERMISSION_DENIED;
4007 }
4008 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004009 }
4010 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004011 return OK;
4012}
4013
4014status_t SurfaceFlinger::onTransact(
4015 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4016{
4017 status_t credentialCheck = CheckTransactCodeCredentials(code);
4018 if (credentialCheck != OK) {
4019 return credentialCheck;
4020 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004021
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004022 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4023 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004024 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004025 IPCThreadState* ipc = IPCThreadState::self();
4026 const int uid = ipc->getCallingUid();
4027 if (CC_UNLIKELY(uid != AID_SYSTEM
4028 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004029 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004030 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004031 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004032 return PERMISSION_DENIED;
4033 }
4034 int n;
4035 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004036 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004037 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004038 return NO_ERROR;
4039 case 1002: // SHOW_UPDATES
4040 n = data.readInt32();
4041 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004042 invalidateHwcGeometry();
4043 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004044 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004045 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004046 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004047 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004048 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004049 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004050 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004051 setTransactionFlags(
4052 eTransactionNeeded|
4053 eDisplayTransactionNeeded|
4054 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004055 return NO_ERROR;
4056 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004057 case 1006:{ // send empty update
4058 signalRefresh();
4059 return NO_ERROR;
4060 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004061 case 1008: // toggle use of hw composer
4062 n = data.readInt32();
4063 mDebugDisableHWC = n ? 1 : 0;
4064 invalidateHwcGeometry();
4065 repaintEverything();
4066 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004067 case 1009: // toggle use of transform hint
4068 n = data.readInt32();
4069 mDebugDisableTransformHint = n ? 1 : 0;
4070 invalidateHwcGeometry();
4071 repaintEverything();
4072 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004073 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004074 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004075 reply->writeInt32(0);
4076 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004077 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004078 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004079 return NO_ERROR;
4080 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004081 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004082 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004083 return NO_ERROR;
4084 }
4085 case 1014: {
4086 // daltonize
4087 n = data.readInt32();
4088 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004089 case 1:
4090 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4091 break;
4092 case 2:
4093 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4094 break;
4095 case 3:
4096 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4097 break;
4098 default:
4099 mDaltonizer.setType(ColorBlindnessType::None);
4100 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004101 }
4102 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004103 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004104 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004105 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004106 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004107 invalidateHwcGeometry();
4108 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004109 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004110 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004111 case 1015: {
4112 // apply a color matrix
4113 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004114 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004115 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004116 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004117 for (size_t j = 0; j < 4; j++) {
4118 mColorMatrix[i][j] = data.readFloat();
4119 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004120 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004121 } else {
4122 mColorMatrix = mat4();
4123 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004124
4125 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4126 // the division by w in the fragment shader
4127 float4 lastRow(transpose(mColorMatrix)[3]);
4128 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4129 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4130 }
4131
Alan Viverette9c5a3332013-09-12 20:04:35 -07004132 invalidateHwcGeometry();
4133 repaintEverything();
4134 return NO_ERROR;
4135 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004136 // This is an experimental interface
4137 // Needs to be shifted to proper binder interface when we productize
4138 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004139 n = data.readInt32();
4140 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004141 return NO_ERROR;
4142 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004143 case 1017: {
4144 n = data.readInt32();
4145 mForceFullDamage = static_cast<bool>(n);
4146 return NO_ERROR;
4147 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004148 case 1018: { // Modify Choreographer's phase offset
4149 n = data.readInt32();
4150 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4151 return NO_ERROR;
4152 }
4153 case 1019: { // Modify SurfaceFlinger's phase offset
4154 n = data.readInt32();
4155 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4156 return NO_ERROR;
4157 }
Irvel468051e2016-06-13 16:44:44 -07004158 case 1020: { // Layer updates interceptor
4159 n = data.readInt32();
4160 if (n) {
4161 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004162 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004163 }
4164 else{
4165 ALOGV("Interceptor disabled");
4166 mInterceptor.disable();
4167 }
4168 return NO_ERROR;
4169 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004170 case 1021: { // Disable HWC virtual displays
4171 n = data.readInt32();
4172 mUseHwcVirtualDisplays = !n;
4173 return NO_ERROR;
4174 }
Romain Guy0147a172017-06-01 13:53:56 -07004175 case 1022: { // Set saturation boost
4176 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4177
4178 invalidateHwcGeometry();
4179 repaintEverything();
4180 return NO_ERROR;
4181 }
Romain Guy54f154a2017-10-24 21:40:32 +01004182 case 1023: { // Set native mode
4183 mForceNativeColorMode = data.readInt32() == 1;
4184
4185 invalidateHwcGeometry();
4186 repaintEverything();
4187 return NO_ERROR;
4188 }
4189 case 1024: { // Is wide color gamut rendering/color management supported?
4190 reply->writeBool(hasWideColorDisplay);
4191 return NO_ERROR;
4192 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004193 }
4194 }
4195 return err;
4196}
4197
Steven Thomas6d8110b2017-08-31 18:24:21 -07004198void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004199 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004200 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004201}
4202
Steven Thomas6d8110b2017-08-31 18:24:21 -07004203void SurfaceFlinger::repaintEverything() {
4204 ConditionalLock _l(mStateLock,
4205 std::this_thread::get_id() != mMainThreadId);
4206 repaintEverythingLocked();
4207}
4208
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004209// Checks that the requested width and height are valid and updates them to the display dimensions
4210// if they are set to 0
4211static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4212 Transform::orientation_flags rotation,
4213 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4214 // get screen geometry
4215 uint32_t displayWidth = displayDevice->getWidth();
4216 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004217
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004218 if (rotation & Transform::ROT_90) {
4219 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004220 }
4221
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004222 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4223 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4224 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4225 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004226 }
4227
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004228 if (*requestedWidth == 0) {
4229 *requestedWidth = displayWidth;
4230 }
4231 if (*requestedHeight == 0) {
4232 *requestedHeight = displayHeight;
4233 }
4234
4235 return NO_ERROR;
4236}
4237
4238// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4239class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004240public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004241 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4242 ~WindowDisconnector() {
4243 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004244 }
4245
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004246private:
4247 ANativeWindow* mWindow;
4248 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004249};
4250
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004251static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4252 uint32_t requestedHeight, bool hasWideColorDisplay,
4253 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4254 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4255 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4256
4257 int err = 0;
4258 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4259 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4260 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4261 err |= native_window_set_usage(window, usage);
4262
4263 if (hasWideColorDisplay) {
4264 err |= native_window_set_buffers_data_space(window,
4265 renderEngineUsesWideColor
4266 ? HAL_DATASPACE_DISPLAY_P3
4267 : HAL_DATASPACE_V0_SRGB);
4268 }
4269
4270 if (err != NO_ERROR) {
4271 return BAD_VALUE;
4272 }
4273
4274 /* TODO: Once we have the sync framework everywhere this can use
4275 * server-side waits on the fence that dequeueBuffer returns.
4276 */
4277 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4278 if (err != NO_ERROR) {
4279 return err;
4280 }
4281
4282 return NO_ERROR;
4283}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004284
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004285status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4286 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004287 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004288 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004289 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004290 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004291
4292 if (CC_UNLIKELY(display == 0))
4293 return BAD_VALUE;
4294
4295 if (CC_UNLIKELY(producer == 0))
4296 return BAD_VALUE;
4297
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004298 // if we have secure windows on this display, never allow the screen capture
4299 // unless the producer interface is local (i.e.: we can take a screenshot for
4300 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004301 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004302
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004303 // Convert to surfaceflinger's internal rotation type.
4304 Transform::orientation_flags rotationFlags;
4305 switch (rotation) {
4306 case ISurfaceComposer::eRotateNone:
4307 rotationFlags = Transform::ROT_0;
4308 break;
4309 case ISurfaceComposer::eRotate90:
4310 rotationFlags = Transform::ROT_90;
4311 break;
4312 case ISurfaceComposer::eRotate180:
4313 rotationFlags = Transform::ROT_180;
4314 break;
4315 case ISurfaceComposer::eRotate270:
4316 rotationFlags = Transform::ROT_270;
4317 break;
4318 default:
4319 rotationFlags = Transform::ROT_0;
4320 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4321 break;
4322 }
4323
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004324 { // Autolock scope
4325 Mutex::Autolock lock(mStateLock);
4326 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4327 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004328 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004329
4330 // create a surface (because we're a producer, and we need to
4331 // dequeue/queue a buffer)
4332 sp<Surface> surface = new Surface(producer, false);
4333
4334 // Put the screenshot Surface into async mode so that
4335 // Layer::headFenceHasSignaled will always return true and we'll latch the
4336 // first buffer regardless of whether or not its acquire fence has
4337 // signaled. This is needed to avoid a race condition in the rotation
4338 // animation. See b/30209608
4339 surface->setAsyncMode(true);
4340
4341 ANativeWindow* window = surface.get();
4342
4343 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4344 if (result != NO_ERROR) {
4345 return result;
4346 }
4347 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4348
4349 ANativeWindowBuffer* buffer = nullptr;
Romain Guy54f154a2017-10-24 21:40:32 +01004350 result = getWindowBuffer(window, reqWidth, reqHeight,
4351 hasWideColorDisplay && !mForceNativeColorMode,
4352 getRenderEngine().usesWideColor(), &buffer);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004353 if (result != NO_ERROR) {
4354 return result;
4355 }
4356
4357 // This mutex protects syncFd and captureResult for communication of the return values from the
4358 // main thread back to this Binder thread
4359 std::mutex captureMutex;
4360 std::condition_variable captureCondition;
4361 std::unique_lock<std::mutex> captureLock(captureMutex);
4362 int syncFd = -1;
4363 std::optional<status_t> captureResult;
4364
4365 sp<LambdaMessage> message = new LambdaMessage([&]() {
4366 // If there is a refresh pending, bug out early and tell the binder thread to try again
4367 // after the refresh.
4368 if (mRefreshPending) {
4369 ATRACE_NAME("Skipping screenshot for now");
4370 std::unique_lock<std::mutex> captureLock(captureMutex);
4371 captureResult = std::make_optional<status_t>(EAGAIN);
4372 captureCondition.notify_one();
4373 return;
4374 }
4375
4376 status_t result = NO_ERROR;
4377 int fd = -1;
4378 {
4379 Mutex::Autolock _l(mStateLock);
4380 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4381 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4382 minLayerZ, maxLayerZ, useIdentityTransform,
4383 rotationFlags, isLocalScreenshot, &fd);
4384 }
4385
4386 {
4387 std::unique_lock<std::mutex> captureLock(captureMutex);
4388 syncFd = fd;
4389 captureResult = std::make_optional<status_t>(result);
4390 captureCondition.notify_one();
4391 }
4392 });
4393
4394 result = postMessageAsync(message);
4395 if (result == NO_ERROR) {
4396 captureCondition.wait(captureLock, [&]() { return captureResult; });
4397 while (*captureResult == EAGAIN) {
4398 captureResult.reset();
4399 result = postMessageAsync(message);
4400 if (result != NO_ERROR) {
4401 return result;
4402 }
4403 captureCondition.wait(captureLock, [&]() { return captureResult; });
4404 }
4405 result = *captureResult;
4406 }
4407
4408 if (result == NO_ERROR) {
4409 // queueBuffer takes ownership of syncFd
4410 result = window->queueBuffer(window, buffer, syncFd);
4411 }
4412
4413 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004414}
4415
Mathias Agopian180f10d2013-04-10 22:55:41 -07004416
4417void SurfaceFlinger::renderScreenImplLocked(
4418 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004419 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004420 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004421 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004422{
4423 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004424 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004425
4426 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004427 const int32_t hw_w = hw->getWidth();
4428 const int32_t hw_h = hw->getHeight();
4429 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004430 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004431
Dan Stozac1879002014-05-22 15:59:05 -07004432 // if a default or invalid sourceCrop is passed in, set reasonable values
4433 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4434 !sourceCrop.isValid()) {
4435 sourceCrop.setLeftTop(Point(0, 0));
4436 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4437 }
4438
4439 // ensure that sourceCrop is inside screen
4440 if (sourceCrop.left < 0) {
4441 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4442 }
Dan Stozabe31f442014-06-11 11:20:54 -07004443 if (sourceCrop.right > hw_w) {
4444 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004445 }
4446 if (sourceCrop.top < 0) {
4447 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4448 }
Dan Stozabe31f442014-06-11 11:20:54 -07004449 if (sourceCrop.bottom > hw_h) {
4450 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004451 }
4452
Romain Guy88d37dd2017-05-26 17:57:05 -07004453#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01004454 engine.setWideColor(hw->getWideColorSupport() && !mForceNativeColorMode);
4455 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE : hw->getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004456#endif
4457
Mathias Agopian180f10d2013-04-10 22:55:41 -07004458 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004459 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004460
4461 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004462 engine.setViewportAndProjection(
4463 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004464 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004465
4466 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004467 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004468
Robert Carr1f0a16a2016-10-24 16:27:39 -07004469 // We loop through the first level of layers without traversing,
4470 // as we need to interpret min/max layer Z in the top level Z space.
4471 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004472 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004473 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004474 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004475 const Layer::State& state(layer->getDrawingState());
4476 if (state.z < minLayerZ || state.z > maxLayerZ) {
4477 continue;
4478 }
Dan Stoza412903f2017-04-27 13:42:17 -07004479 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004480 if (!layer->isVisible()) {
4481 return;
4482 }
4483 if (filtering) layer->setFiltering(true);
4484 layer->draw(hw, useIdentityTransform);
4485 if (filtering) layer->setFiltering(false);
4486 });
4487 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004488
Mathias Agopian931bda12013-08-28 18:11:46 -07004489 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004490}
4491
Dan Stozaabcda352017-06-01 14:37:39 -07004492// A simple RAII class that holds an EGLImage and destroys it either:
4493// a) When the destroy() method is called
4494// b) When the object goes out of scope
4495class ImageHolder {
4496public:
4497 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4498 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004499
Dan Stozaabcda352017-06-01 14:37:39 -07004500 void destroy() {
4501 if (mImage != EGL_NO_IMAGE_KHR) {
4502 eglDestroyImageKHR(mDisplay, mImage);
4503 mImage = EGL_NO_IMAGE_KHR;
4504 }
4505 }
4506
4507private:
4508 const EGLDisplay mDisplay;
4509 EGLImageKHR mImage;
4510};
4511
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004512status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4513 ANativeWindowBuffer* buffer, Rect sourceCrop,
4514 uint32_t reqWidth, uint32_t reqHeight,
4515 int32_t minLayerZ, int32_t maxLayerZ,
4516 bool useIdentityTransform,
4517 Transform::orientation_flags rotation,
4518 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004519 ATRACE_CALL();
4520
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004521 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004522 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004523 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004524 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004525 (state.z < minLayerZ || state.z > maxLayerZ)) {
4526 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004527 }
Dan Stoza412903f2017-04-27 13:42:17 -07004528 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004529 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4530 layer->isSecure());
4531 });
4532 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004533
4534 if (!isLocalScreenshot && secureLayerIsVisible) {
4535 ALOGW("FB is protected: PERMISSION_DENIED");
4536 return PERMISSION_DENIED;
4537 }
4538
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004539 int syncFd = -1;
4540 // create an EGLImage from the buffer so we can later
4541 // turn it into a texture
4542 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4543 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4544 if (image == EGL_NO_IMAGE_KHR) {
4545 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004546 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004547
Dan Stozaabcda352017-06-01 14:37:39 -07004548 // This will automatically destroy the image if we return before calling its destroy method
4549 ImageHolder imageHolder(mEGLDisplay, image);
4550
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004551 // this binds the given EGLImage as a framebuffer for the
4552 // duration of this scope.
4553 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004554 if (imageBond.getStatus() != NO_ERROR) {
4555 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004556 return INVALID_OPERATION;
4557 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004558
Dan Stozaabcda352017-06-01 14:37:39 -07004559 // this will in fact render into our dequeued buffer
4560 // via an FBO, which means we didn't have to create
4561 // an EGLSurface and therefore we're not
4562 // dependent on the context's EGLConfig.
4563 renderScreenImplLocked(
4564 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4565 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004566
Dan Stozaabcda352017-06-01 14:37:39 -07004567 // Attempt to create a sync khr object that can produce a sync point. If that
4568 // isn't available, create a non-dupable sync object in the fallback path and
4569 // wait on it directly.
4570 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4571 if (!DEBUG_SCREENSHOTS) {
4572 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4573 // native fence fd will not be populated until flush() is done.
4574 getRenderEngine().flush();
4575 }
4576
4577 if (sync != EGL_NO_SYNC_KHR) {
4578 // get the sync fd
4579 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4580 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4581 ALOGW("captureScreen: failed to dup sync khr object");
4582 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004583 }
Dan Stozaabcda352017-06-01 14:37:39 -07004584 eglDestroySyncKHR(mEGLDisplay, sync);
4585 } else {
4586 // fallback path
4587 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004588 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004589 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4590 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4591 EGLint eglErr = eglGetError();
4592 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4593 ALOGW("captureScreen: fence wait timed out");
4594 } else {
4595 ALOGW_IF(eglErr != EGL_SUCCESS,
4596 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004597 }
4598 eglDestroySyncKHR(mEGLDisplay, sync);
4599 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004600 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004601 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004602 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004603 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004604
4605 if (DEBUG_SCREENSHOTS) {
4606 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4607 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4608 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4609 hw, minLayerZ, maxLayerZ);
4610 delete [] pixels;
4611 }
4612
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004613 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004614 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004615
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004616 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004617}
4618
Mathias Agopiand5556842013-09-19 17:08:37 -07004619void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004620 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004621 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004622 for (size_t y=0 ; y<h ; y++) {
4623 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4624 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004625 if (p[x] != 0xFF000000) return;
4626 }
4627 }
4628 ALOGE("*** we just took a black screenshot ***\n"
4629 "requested minz=%d, maxz=%d, layerStack=%d",
4630 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004631
Robert Carr2047fae2016-11-28 14:09:09 -08004632 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004633 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004634 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004635 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004636 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004637 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004638 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4639 layer->isVisible() ? '+' : '-',
4640 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004641 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004642 i++;
4643 });
4644 }
4645 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004646 }
4647}
4648
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004649// ---------------------------------------------------------------------------
4650
Dan Stoza412903f2017-04-27 13:42:17 -07004651void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4652 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004653}
4654
Dan Stoza412903f2017-04-27 13:42:17 -07004655void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4656 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004657}
4658
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004659}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004660
4661
4662#if defined(__gl_h_)
4663#error "don't include gl/gl.h in this file"
4664#endif
4665
4666#if defined(__gl2_h_)
4667#error "don't include gl2/gl2.h in this file"
4668#endif