blob: 33278ae59e0c23f36581c9f5261613832bdbba9a [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
31#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080040#include <dvr/vr_flinger.h>
41
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060042#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070044#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070045
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080049#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080050#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051
52#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080055
Mathias Agopiancde87a32012-09-13 14:09:01 -070056#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/String8.h>
58#include <utils/String16.h>
59#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070060#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian921e6ac2012-07-23 23:11:29 -070063#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070064#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070070#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093#define DISPLAY_COUNT 1
94
Mathias Agopianfee2b462013-07-03 12:34:01 -070095/*
96 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
97 * black pixels.
98 */
99#define DEBUG_SCREENSHOTS false
100
Jiyong Park00b15b82017-08-10 20:30:56 +0900101extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
Mathias Agopianca088332013-03-28 17:44:13 -0700102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
Steven Thomasb02664d2017-07-26 18:48:28 -0700108namespace {
109class ConditionalLock {
110public:
111 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
112 if (lock) {
113 mMutex.lock();
114 }
115 }
116 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
117private:
118 Mutex& mMutex;
119 bool mLocked;
120};
121} // namespace anonymous
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800131int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
132int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700133bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700134int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700135bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800136uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800137bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800138bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800139int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700158 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700160 mTransactionPending(false),
161 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700162 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700163 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700164 mRepaintEverything(0),
Kalle Raitaa099a242017-01-11 11:17:29 -0800165 mHwcServiceName(getHwcServiceName()),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800166 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800168 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800170 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800171 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800172 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700173 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700174 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700175 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700176 mDebugInSwapBuffers(0),
177 mLastSwapBufferTime(0),
178 mDebugInTransaction(0),
179 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700180 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700181 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800182 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000183 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700184 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700185 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700186 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800187 mHasPoweredOff(false),
188 mFrameBuckets(),
189 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700190 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800191 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700192 mVrFlingerRequestsDisplay(false),
193 mMainThreadId(std::this_thread::get_id()),
194 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800196 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800197
198 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
199 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
200
201 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
202 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
203
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800204 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
205 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700207 useContextPriority = getBool< ISurfaceFlingerConfigs,
208 &ISurfaceFlingerConfigs::useContextPriority>(false);
209
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700210 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
211 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
212
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700213 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
214 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
215
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
217 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
218
Steven Thomas050b2c82017-03-06 11:45:16 -0800219 // Vr flinger is only enabled on Daydream ready devices.
220 useVrFlinger = getBool< ISurfaceFlingerConfigs,
221 &ISurfaceFlingerConfigs::useVrFlinger>(false);
222
Fabien Sanglard1971b632017-03-10 14:50:03 -0800223 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
224 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
225
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600226 hasWideColorDisplay =
227 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
228
Saurabh Shahf4174532017-07-13 10:45:07 -0700229 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
230
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 // debugging stuff...
232 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700233
Mathias Agopianb4b17302013-03-20 18:36:41 -0700234 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700235 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 property_get("debug.sf.showupdates", value, "0");
238 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240 property_get("debug.sf.ddms", value, "0");
241 mDebugDDMS = atoi(value);
242 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700243 if (!startDdmConnection()) {
244 // start failed, and DDMS debugging not enabled
245 mDebugDDMS = 0;
246 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700247 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700248 ALOGI_IF(mDebugRegion, "showupdates enabled");
249 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700250
251 property_get("debug.sf.disable_backpressure", value, "0");
252 mPropagateBackpressure = !atoi(value);
253 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700254
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800255 property_get("debug.sf.enable_hwc_vds", value, "0");
256 mUseHwcVirtualDisplays = atoi(value);
257 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800258
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800259 property_get("ro.sf.disable_triple_buffer", value, "1");
260 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800261 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700262
Romain Guy11d63f42017-07-20 12:47:14 -0700263 // We should be reading 'persist.sys.sf.color_saturation' here
264 // but since /data may be encrypted, we need to wait until after vold
265 // comes online to attempt to read the property. The property is
266 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800267
268 if (useTrebleTestingOverride()) {
269 // Without the override SurfaceFlinger cannot connect to HIDL
270 // services that are not listed in the manifests. Considered
271 // deriving the setting from the set service name, but it
272 // would be brittle if the name that's not 'default' is used
273 // for production purposes later on.
274 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800278void SurfaceFlinger::onFirstRef()
279{
280 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800281}
282
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283SurfaceFlinger::~SurfaceFlinger()
284{
Mathias Agopiana4912602012-07-12 14:25:33 -0700285 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
286 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
287 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288}
289
Dan Stozac7014012014-02-14 15:03:43 -0800290void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800291{
292 // the window manager died on us. prepare its eulogy.
293
Andy McFadden13a082e2012-08-24 10:16:42 -0700294 // restore initial conditions (default device unblank, etc)
295 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800296
297 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700298 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800299}
300
Robert Carr1db73f62016-12-21 12:58:51 -0800301static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700302 status_t err = client->initCheck();
303 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800304 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 }
Robert Carr1db73f62016-12-21 12:58:51 -0800306 return nullptr;
307}
308
309sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
310 return initClient(new Client(this));
311}
312
313sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
314 const sp<IGraphicBufferProducer>& gbp) {
315 if (authenticateSurfaceTexture(gbp) == false) {
316 return nullptr;
317 }
318 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
319 if (layer == nullptr) {
320 return nullptr;
321 }
322
323 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324}
325
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700326sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
327 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700328{
329 class DisplayToken : public BBinder {
330 sp<SurfaceFlinger> flinger;
331 virtual ~DisplayToken() {
332 // no more references, this display must be terminated
333 Mutex::Autolock _l(flinger->mStateLock);
334 flinger->mCurrentState.displays.removeItem(this);
335 flinger->setTransactionFlags(eDisplayTransactionNeeded);
336 }
337 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700338 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700339 : flinger(flinger) {
340 }
341 };
342
343 sp<BBinder> token = new DisplayToken(this);
344
345 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700346 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700347 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700348 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700349 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700350 return token;
351}
352
Jesse Hall6c913be2013-08-08 12:15:49 -0700353void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
354 Mutex::Autolock _l(mStateLock);
355
356 ssize_t idx = mCurrentState.displays.indexOfKey(display);
357 if (idx < 0) {
358 ALOGW("destroyDisplay: invalid display token");
359 return;
360 }
361
362 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
363 if (!info.isVirtualDisplay()) {
364 ALOGE("destroyDisplay called for non-virtual display");
365 return;
366 }
Irvelffc9efc2016-07-27 15:16:37 -0700367 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700368 mCurrentState.displays.removeItemsAt(idx);
369 setTransactionFlags(eDisplayTransactionNeeded);
370}
371
Jesse Hall692c7232012-11-08 15:41:56 -0800372void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800373 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800374 ALOGW_IF(mBuiltinDisplays[type],
375 "Overwriting display token for display type %d", type);
376 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800377 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700378 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800379 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700380 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800381}
382
Mathias Agopiane57f2922012-08-09 16:29:12 -0700383sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700384 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700385 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
386 return NULL;
387 }
Jesse Hall692c7232012-11-08 15:41:56 -0800388 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700389}
390
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800391void SurfaceFlinger::bootFinished()
392{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700393 if (mStartPropertySetThread->join() != NO_ERROR) {
394 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800395 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396 const nsecs_t now = systemTime();
397 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000398 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700399
400 // wait patiently for the window manager death
401 const String16 name("window");
402 sp<IBinder> window(defaultServiceManager()->getService(name));
403 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700404 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700405 }
406
Steven Thomas050b2c82017-03-06 11:45:16 -0800407 if (mVrFlinger) {
408 mVrFlinger->OnBootFinished();
409 }
410
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700411 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700412 // formerly we would just kill the process, but we now ask it to exit so it
413 // can choose where to stop the animation.
414 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700415
416 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
417 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
418 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700419
Thierry Strudel2924d012017-08-14 15:19:37 -0700420 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700421 readPersistentProperties();
422 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700423 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Mathias Agopian3f844832013-08-07 21:24:32 -0700426void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700427 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700428 RenderEngine& engine;
429 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700430 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700431 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
432 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700433 }
434 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700435 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700436 return true;
437 }
438 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700439 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700440}
441
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442class DispSyncSource : public VSyncSource, private DispSync::Callback {
443public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700444 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000445 const char* name) :
446 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700447 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700448 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000449 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
450 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700451 mDispSync(dispSync),
452 mCallbackMutex(),
453 mCallback(),
454 mVsyncMutex(),
455 mPhaseOffset(phaseOffset),
456 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700457
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 virtual ~DispSyncSource() {}
459
460 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700461 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000463 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700464 static_cast<DispSync::Callback*>(this));
465 if (err != NO_ERROR) {
466 ALOGE("error registering vsync callback: %s (%d)",
467 strerror(-err), err);
468 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700469 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470 } else {
471 status_t err = mDispSync->removeEventListener(
472 static_cast<DispSync::Callback*>(this));
473 if (err != NO_ERROR) {
474 ALOGE("error unregistering vsync callback: %s (%d)",
475 strerror(-err), err);
476 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700477 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700478 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700479 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 }
481
482 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700483 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700484 mCallback = callback;
485 }
486
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700487 virtual void setPhaseOffset(nsecs_t phaseOffset) {
488 Mutex::Autolock lock(mVsyncMutex);
489
490 // Normalize phaseOffset to [0, period)
491 auto period = mDispSync->getPeriod();
492 phaseOffset %= period;
493 if (phaseOffset < 0) {
494 // If we're here, then phaseOffset is in (-period, 0). After this
495 // operation, it will be in (0, period)
496 phaseOffset += period;
497 }
498 mPhaseOffset = phaseOffset;
499
500 // If we're not enabled, we don't need to mess with the listeners
501 if (!mEnabled) {
502 return;
503 }
504
505 // Remove the listener with the old offset
506 status_t err = mDispSync->removeEventListener(
507 static_cast<DispSync::Callback*>(this));
508 if (err != NO_ERROR) {
509 ALOGE("error unregistering vsync callback: %s (%d)",
510 strerror(-err), err);
511 }
512
513 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000514 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700515 static_cast<DispSync::Callback*>(this));
516 if (err != NO_ERROR) {
517 ALOGE("error registering vsync callback: %s (%d)",
518 strerror(-err), err);
519 }
520 }
521
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522private:
523 virtual void onDispSyncEvent(nsecs_t when) {
524 sp<VSyncSource::Callback> callback;
525 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700526 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527 callback = mCallback;
528
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700529 if (mTraceVsync) {
530 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700531 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700532 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533 }
534
535 if (callback != NULL) {
536 callback->onVSyncEvent(when);
537 }
538 }
539
Tim Murray4a4e4a22016-04-19 16:29:23 +0000540 const char* const mName;
541
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 int mValue;
543
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700544 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700545 const String8 mVsyncOnLabel;
546 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700547
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700548 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700549
550 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700551 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700552
553 Mutex mVsyncMutex; // Protects the following
554 nsecs_t mPhaseOffset;
555 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700556};
557
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700558class InjectVSyncSource : public VSyncSource {
559public:
560 InjectVSyncSource() {}
561
562 virtual ~InjectVSyncSource() {}
563
564 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
565 std::lock_guard<std::mutex> lock(mCallbackMutex);
566 mCallback = callback;
567 }
568
569 virtual void onInjectSyncEvent(nsecs_t when) {
570 std::lock_guard<std::mutex> lock(mCallbackMutex);
571 mCallback->onVSyncEvent(when);
572 }
573
574 virtual void setVSyncEnabled(bool) {}
575 virtual void setPhaseOffset(nsecs_t) {}
576
577private:
578 std::mutex mCallbackMutex; // Protects the following
579 sp<VSyncSource::Callback> mCallback;
580};
581
Wei Wangf9b05ee2017-07-19 20:59:39 -0700582// Do not call property_set on main thread which will be blocked by init
583// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700584void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700585 ALOGI( "SurfaceFlinger's main thread ready to run. "
586 "Initializing graphics H/W...");
587
Thierry Strudel2924d012017-08-14 15:19:37 -0700588 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900589
Steven Thomasb02664d2017-07-26 18:48:28 -0700590 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800591
Steven Thomasb02664d2017-07-26 18:48:28 -0700592 // initialize EGL for the default display
593 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
594 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800595
Steven Thomasb02664d2017-07-26 18:48:28 -0700596 // start the EventThread
597 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
598 vsyncPhaseOffsetNs, true, "app");
599 mEventThread = new EventThread(vsyncSrc, *this, false);
600 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
601 sfVsyncPhaseOffsetNs, true, "sf");
602 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
603 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800604
Steven Thomasb02664d2017-07-26 18:48:28 -0700605 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
606 struct sched_param param = {0};
607 param.sched_priority = 2;
608 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
609 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
610 }
611 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
612 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800613 }
614
Steven Thomasb02664d2017-07-26 18:48:28 -0700615 // Get a RenderEngine for the given display / config (can't fail)
616 mRenderEngine = RenderEngine::create(mEGLDisplay,
617 HAL_PIXEL_FORMAT_RGBA_8888,
618 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 // retrieve the EGL context that was selected/created
621 mEGLContext = mRenderEngine->getEGLContext();
622
623 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
624 "couldn't create EGLContext");
625
626 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
627 "Starting with vr flinger active is not currently supported.");
628 mHwc.reset(new HWComposer(mHwcServiceName));
629 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800630
Steven Thomas050b2c82017-03-06 11:45:16 -0800631 if (useVrFlinger) {
632 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700633 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800634 mVrFlingerRequestsDisplay = requestDisplay;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700635 ConditionalLock _l(mStateLock,
636 std::this_thread::get_id() != mMainThreadId);
Steven Thomas050b2c82017-03-06 11:45:16 -0800637 signalTransaction();
638 };
639 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
640 vrFlingerRequestDisplayCallback);
641 if (!mVrFlinger) {
642 ALOGE("Failed to start vrflinger");
643 }
644 }
645
Jamie Gennisd1700752013-10-14 12:22:52 -0700646 mEventControlThread = new EventControlThread(this);
647 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
648
Mathias Agopian92a979a2012-08-02 18:32:23 -0700649 // initialize our drawing state
650 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700651
Andy McFadden13a082e2012-08-24 10:16:42 -0700652 // set initial conditions (e.g. unblank default device)
653 initializeDisplays();
654
Dan Stoza4e637772016-07-28 13:31:51 -0700655 mRenderEngine->primeCache();
656
Wei Wangf9b05ee2017-07-19 20:59:39 -0700657 // Inform native graphics APIs whether the present timestamp is supported:
658 if (getHwComposer().hasCapability(
659 HWC2::Capability::PresentFenceIsNotReliable)) {
660 mStartPropertySetThread = new StartPropertySetThread(false);
661 } else {
662 mStartPropertySetThread = new StartPropertySetThread(true);
663 }
664
665 if (mStartPropertySetThread->Start() != NO_ERROR) {
666 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800667 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800668
Dan Stoza9e56aa02015-11-02 13:00:03 -0800669 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700670}
671
Romain Guy11d63f42017-07-20 12:47:14 -0700672void SurfaceFlinger::readPersistentProperties() {
673 char value[PROPERTY_VALUE_MAX];
674
675 property_get("persist.sys.sf.color_saturation", value, "1.0");
676 mSaturation = atof(value);
677 ALOGV("Saturation is set to %.2f", mSaturation);
678}
679
Mathias Agopiana67e4182012-06-19 17:26:12 -0700680void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800681 // Start boot animation service by setting a property mailbox
682 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700683 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800684 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700685 if (mStartPropertySetThread->join() != NO_ERROR) {
686 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800687 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700688}
689
Mathias Agopian875d8e12013-06-07 15:35:48 -0700690size_t SurfaceFlinger::getMaxTextureSize() const {
691 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700692}
693
Mathias Agopian875d8e12013-06-07 15:35:48 -0700694size_t SurfaceFlinger::getMaxViewportDims() const {
695 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700696}
697
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800698// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800699
Jamie Gennis582270d2011-08-17 18:19:00 -0700700bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800701 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800702 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800703 return authenticateSurfaceTextureLocked(bufferProducer);
704}
705
706bool SurfaceFlinger::authenticateSurfaceTextureLocked(
707 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800708 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700709 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800710}
711
Brian Anderson6b376712017-04-04 10:51:39 -0700712status_t SurfaceFlinger::getSupportedFrameTimestamps(
713 std::vector<FrameEvent>* outSupported) const {
714 *outSupported = {
715 FrameEvent::REQUESTED_PRESENT,
716 FrameEvent::ACQUIRE,
717 FrameEvent::LATCH,
718 FrameEvent::FIRST_REFRESH_START,
719 FrameEvent::LAST_REFRESH_START,
720 FrameEvent::GPU_COMPOSITION_DONE,
721 FrameEvent::DEQUEUE_READY,
722 FrameEvent::RELEASE,
723 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700724 ConditionalLock _l(mStateLock,
725 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700726 if (!getHwComposer().hasCapability(
727 HWC2::Capability::PresentFenceIsNotReliable)) {
728 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
729 }
730 return NO_ERROR;
731}
732
Dan Stoza7f7da322014-05-02 15:26:25 -0700733status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
734 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700735 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700736 return BAD_VALUE;
737 }
738
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500739 if (!display.get())
740 return NAME_NOT_FOUND;
741
Jesse Hall692c7232012-11-08 15:41:56 -0800742 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700743 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800744 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700745 type = i;
746 break;
747 }
748 }
749
750 if (type < 0) {
751 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700752 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700753
Mathias Agopian8b736f12012-08-13 17:54:26 -0700754 // TODO: Not sure if display density should handled by SF any longer
755 class Density {
756 static int getDensityFromProperty(char const* propName) {
757 char property[PROPERTY_VALUE_MAX];
758 int density = 0;
759 if (property_get(propName, property, NULL) > 0) {
760 density = atoi(property);
761 }
762 return density;
763 }
764 public:
765 static int getEmuDensity() {
766 return getDensityFromProperty("qemu.sf.lcd_density"); }
767 static int getBuildDensity() {
768 return getDensityFromProperty("ro.sf.lcd_density"); }
769 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700770
Dan Stoza7f7da322014-05-02 15:26:25 -0700771 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700772
Steven Thomas6d8110b2017-08-31 18:24:21 -0700773 ConditionalLock _l(mStateLock,
774 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800775 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700776 DisplayInfo info = DisplayInfo();
777
Dan Stoza9e56aa02015-11-02 13:00:03 -0800778 float xdpi = hwConfig->getDpiX();
779 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700780
781 if (type == DisplayDevice::DISPLAY_PRIMARY) {
782 // The density of the device is provided by a build property
783 float density = Density::getBuildDensity() / 160.0f;
784 if (density == 0) {
785 // the build doesn't provide a density -- this is wrong!
786 // use xdpi instead
787 ALOGE("ro.sf.lcd_density must be defined as a build property");
788 density = xdpi / 160.0f;
789 }
790 if (Density::getEmuDensity()) {
791 // if "qemu.sf.lcd_density" is specified, it overrides everything
792 xdpi = ydpi = density = Density::getEmuDensity();
793 density /= 160.0f;
794 }
795 info.density = density;
796
797 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700798 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000799 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700800 } else {
801 // TODO: where should this value come from?
802 static const int TV_DENSITY = 213;
803 info.density = TV_DENSITY / 160.0f;
804 info.orientation = 0;
805 }
806
Dan Stoza9e56aa02015-11-02 13:00:03 -0800807 info.w = hwConfig->getWidth();
808 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700809 info.xdpi = xdpi;
810 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800811 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900812 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800813
Andy McFadden91b2ca82014-06-13 14:04:23 -0700814 // This is how far in advance a buffer must be queued for
815 // presentation at a given time. If you want a buffer to appear
816 // on the screen at time N, you must submit the buffer before
817 // (N - presentationDeadline).
818 //
819 // Normally it's one full refresh period (to give SF a chance to
820 // latch the buffer), but this can be reduced by configuring a
821 // DispSync offset. Any additional delays introduced by the hardware
822 // composer or panel must be accounted for here.
823 //
824 // We add an additional 1ms to allow for processing time and
825 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800827 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700828
829 // All non-virtual displays are currently considered secure.
830 info.secure = true;
831
Michael Wright28f24d02016-07-12 13:30:53 -0700832 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 }
834
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 return NO_ERROR;
836}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700837
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800838status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700839 DisplayStatInfo* stats) {
840 if (stats == NULL) {
841 return BAD_VALUE;
842 }
843
844 // FIXME for now we always return stats for the primary display
845 memset(stats, 0, sizeof(*stats));
846 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
847 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
848 return NO_ERROR;
849}
850
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700851int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800852 if (display == NULL) {
853 ALOGE("%s : display is NULL", __func__);
854 return BAD_VALUE;
855 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700856
857 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700858 if (device != NULL) {
859 return device->getActiveConfig();
860 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700861
Dan Stoza24a42e92015-03-09 10:04:11 -0700862 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700863}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700864
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700865void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
866 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
867 this);
868 int32_t type = hw->getDisplayType();
869 int currentMode = hw->getActiveConfig();
870
871 if (mode == currentMode) {
872 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
873 return;
874 }
875
876 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
877 ALOGW("Trying to set config for virtual display");
878 return;
879 }
880
881 hw->setActiveConfig(mode);
882 getHwComposer().setActiveConfig(type, mode);
883}
884
885status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
886 class MessageSetActiveConfig: public MessageBase {
887 SurfaceFlinger& mFlinger;
888 sp<IBinder> mDisplay;
889 int mMode;
890 public:
891 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
892 int mode) :
893 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
894 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700895 Vector<DisplayInfo> configs;
896 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700897 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700898 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700899 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700900 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700901 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700902 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
903 if (hw == NULL) {
904 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700905 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700906 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
907 ALOGW("Attempt to set active config = %d for virtual display",
908 mMode);
909 } else {
910 mFlinger.setActiveConfigInternal(hw, mMode);
911 }
912 return true;
913 }
914 };
915 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
916 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700917 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700918}
Michael Wright28f24d02016-07-12 13:30:53 -0700919status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
920 Vector<android_color_mode_t>* outColorModes) {
921 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
922 return BAD_VALUE;
923 }
924
925 if (!display.get()) {
926 return NAME_NOT_FOUND;
927 }
928
929 int32_t type = NAME_NOT_FOUND;
930 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
931 if (display == mBuiltinDisplays[i]) {
932 type = i;
933 break;
934 }
935 }
936
937 if (type < 0) {
938 return type;
939 }
940
Steven Thomas6d8110b2017-08-31 18:24:21 -0700941 std::vector<android_color_mode_t> modes;
942 {
943 ConditionalLock _l(mStateLock,
944 std::this_thread::get_id() != mMainThreadId);
945 modes = getHwComposer().getColorModes(type);
946 }
Michael Wright28f24d02016-07-12 13:30:53 -0700947 outColorModes->clear();
948 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
949
950 return NO_ERROR;
951}
952
953android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700954 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700955 if (device != nullptr) {
956 return device->getActiveColorMode();
957 }
958 return static_cast<android_color_mode_t>(BAD_VALUE);
959}
960
961void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
962 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700963 int32_t type = hw->getDisplayType();
964 android_color_mode_t currentMode = hw->getActiveColorMode();
965
966 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700967 return;
968 }
969
970 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
971 ALOGW("Trying to set config for virtual display");
972 return;
973 }
974
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600975 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
976 hw->getDisplayType());
977
Michael Wright28f24d02016-07-12 13:30:53 -0700978 hw->setActiveColorMode(mode);
979 getHwComposer().setActiveColorMode(type, mode);
980}
981
982
983status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
984 android_color_mode_t colorMode) {
985 class MessageSetActiveColorMode: public MessageBase {
986 SurfaceFlinger& mFlinger;
987 sp<IBinder> mDisplay;
988 android_color_mode_t mMode;
989 public:
990 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
991 android_color_mode_t mode) :
992 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
993 virtual bool handler() {
994 Vector<android_color_mode_t> modes;
995 mFlinger.getDisplayColorModes(mDisplay, &modes);
996 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
997 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600998 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
999 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001000 return true;
1001 }
1002 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1003 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001004 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1005 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001006 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001007 ALOGW("Attempt to set active color mode %s %d for virtual display",
1008 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001009 } else {
1010 mFlinger.setActiveColorModeInternal(hw, mMode);
1011 }
1012 return true;
1013 }
1014 };
1015 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1016 postMessageSync(msg);
1017 return NO_ERROR;
1018}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001019
Svetoslavd85084b2014-03-20 10:28:31 -07001020status_t SurfaceFlinger::clearAnimationFrameStats() {
1021 Mutex::Autolock _l(mStateLock);
1022 mAnimFrameTracker.clearStats();
1023 return NO_ERROR;
1024}
1025
1026status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1027 Mutex::Autolock _l(mStateLock);
1028 mAnimFrameTracker.getStats(outStats);
1029 return NO_ERROR;
1030}
1031
Dan Stozac4f471e2016-03-24 09:31:08 -07001032status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1033 HdrCapabilities* outCapabilities) const {
1034 Mutex::Autolock _l(mStateLock);
1035
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001036 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001037 if (displayDevice == nullptr) {
1038 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1039 return BAD_VALUE;
1040 }
1041
1042 std::unique_ptr<HdrCapabilities> capabilities =
1043 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1044 if (capabilities) {
1045 std::swap(*outCapabilities, *capabilities);
1046 } else {
1047 return BAD_VALUE;
1048 }
1049
1050 return NO_ERROR;
1051}
1052
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001053status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1054 if (enable == mInjectVSyncs) {
1055 return NO_ERROR;
1056 }
1057
1058 if (enable) {
1059 mInjectVSyncs = enable;
1060 ALOGV("VSync Injections enabled");
1061 if (mVSyncInjector.get() == nullptr) {
1062 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001063 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001064 }
1065 mEventQueue.setEventThread(mInjectorEventThread);
1066 } else {
1067 mInjectVSyncs = enable;
1068 ALOGV("VSync Injections disabled");
1069 mEventQueue.setEventThread(mSFEventThread);
1070 mVSyncInjector.clear();
1071 }
1072 return NO_ERROR;
1073}
1074
1075status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1076 if (!mInjectVSyncs) {
1077 ALOGE("VSync Injections not enabled");
1078 return BAD_VALUE;
1079 }
1080 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1081 ALOGV("Injecting VSync inside SurfaceFlinger");
1082 mVSyncInjector->onInjectSyncEvent(when);
1083 }
1084 return NO_ERROR;
1085}
1086
Kalle Raitaa099a242017-01-11 11:17:29 -08001087status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1088 IPCThreadState* ipc = IPCThreadState::self();
1089 const int pid = ipc->getCallingPid();
1090 const int uid = ipc->getCallingUid();
1091 if ((uid != AID_SHELL) &&
1092 !PermissionCache::checkPermission(sDump, pid, uid)) {
1093 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1094 return PERMISSION_DENIED;
1095 }
1096
1097 // Try to acquire a lock for 1s, fail gracefully
1098 const status_t err = mStateLock.timedLock(s2ns(1));
1099 const bool locked = (err == NO_ERROR);
1100 if (!locked) {
1101 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1102 return TIMED_OUT;
1103 }
1104
1105 outLayers->clear();
1106 mCurrentState.traverseInZOrder([&](Layer* layer) {
1107 outLayers->push_back(layer->getLayerDebugInfo());
1108 });
1109
1110 mStateLock.unlock();
1111 return NO_ERROR;
1112}
1113
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001114// ----------------------------------------------------------------------------
1115
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001116sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1117 ISurfaceComposer::VsyncSource vsyncSource) {
1118 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1119 return mSFEventThread->createEventConnection();
1120 } else {
1121 return mEventThread->createEventConnection();
1122 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001123}
1124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001125// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001126
1127void SurfaceFlinger::waitForEvent() {
1128 mEventQueue.waitMessage();
1129}
1130
1131void SurfaceFlinger::signalTransaction() {
1132 mEventQueue.invalidate();
1133}
1134
1135void SurfaceFlinger::signalLayerUpdate() {
1136 mEventQueue.invalidate();
1137}
1138
1139void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001140 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001141 mEventQueue.refresh();
1142}
1143
1144status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001145 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001146 return mEventQueue.postMessage(msg, reltime);
1147}
1148
1149status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001150 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001151 status_t res = mEventQueue.postMessage(msg, reltime);
1152 if (res == NO_ERROR) {
1153 msg->wait();
1154 }
1155 return res;
1156}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001157
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001158void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001159 do {
1160 waitForEvent();
1161 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001162}
1163
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001164void SurfaceFlinger::enableHardwareVsync() {
1165 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001166 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001167 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001168 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1169 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001170 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001171 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001172}
1173
Jesse Hall948fe0c2013-10-14 12:56:09 -07001174void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001175 Mutex::Autolock _l(mHWVsyncLock);
1176
Jesse Hall948fe0c2013-10-14 12:56:09 -07001177 if (makeAvailable) {
1178 mHWVsyncAvailable = true;
1179 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001180 // Hardware vsync is not currently available, so abort the resync
1181 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001182 return;
1183 }
1184
Dan Stoza9e56aa02015-11-02 13:00:03 -08001185 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1186 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187
1188 mPrimaryDispSync.reset();
1189 mPrimaryDispSync.setPeriod(period);
1190
1191 if (!mPrimaryHWVsyncEnabled) {
1192 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001193 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1194 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195 mPrimaryHWVsyncEnabled = true;
1196 }
1197}
1198
Jesse Hall948fe0c2013-10-14 12:56:09 -07001199void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001200 Mutex::Autolock _l(mHWVsyncLock);
1201 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001202 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1203 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001204 mPrimaryDispSync.endResync();
1205 mPrimaryHWVsyncEnabled = false;
1206 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001207 if (makeUnavailable) {
1208 mHWVsyncAvailable = false;
1209 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001210}
1211
Tim Murray4a4e4a22016-04-19 16:29:23 +00001212void SurfaceFlinger::resyncWithRateLimit() {
1213 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001214
1215 // No explicit locking is needed here since EventThread holds a lock while calling this method
1216 static nsecs_t sLastResyncAttempted = 0;
1217 const nsecs_t now = systemTime();
1218 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001219 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001220 }
Dan Stoza57164302017-05-08 14:03:54 -07001221 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001222}
1223
Steven Thomasb02664d2017-07-26 18:48:28 -07001224void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1225 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001226 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001227 // Ignore any vsyncs from a previous hardware composer.
1228 if (sequenceId != mComposerSequenceId) {
1229 return;
1230 }
1231
1232 int32_t type;
1233 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001234 return;
1235 }
1236
Jamie Gennisd1700752013-10-14 12:22:52 -07001237 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238
Jamie Gennisd1700752013-10-14 12:22:52 -07001239 { // Scope for the lock
1240 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001241 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001242 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001243 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001244 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001245
1246 if (needsHwVsync) {
1247 enableHardwareVsync();
1248 } else {
1249 disableHardwareVsync(false);
1250 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001251}
1252
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001253void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001254 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001255 *compositorTiming = mCompositorTiming;
1256}
1257
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001258void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001259 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001260 wp<IBinder> token = mBuiltinDisplays[type];
1261
1262 // All non-virtual displays are currently considered secure.
1263 const bool isSecure = true;
1264
1265 sp<IGraphicBufferProducer> producer;
1266 sp<IGraphicBufferConsumer> consumer;
1267 BufferQueue::createBufferQueue(&producer, &consumer);
1268
1269 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1270
1271 bool hasWideColorModes = false;
1272 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1273 for (android_color_mode_t colorMode : modes) {
1274 switch (colorMode) {
1275 case HAL_COLOR_MODE_DISPLAY_P3:
1276 case HAL_COLOR_MODE_ADOBE_RGB:
1277 case HAL_COLOR_MODE_DCI_P3:
1278 hasWideColorModes = true;
1279 break;
1280 default:
1281 break;
1282 }
1283 }
1284 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1285 token, fbs, producer, mRenderEngine->getEGLConfig(),
1286 hasWideColorModes && hasWideColorDisplay);
1287 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001288 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1289 if (hasWideColorModes && hasWideColorDisplay) {
1290 defaultColorMode = HAL_COLOR_MODE_SRGB;
1291 }
1292 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001293 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001294
1295 // Add the primary display token to mDrawingState so we don't try to
1296 // recreate the DisplayDevice for the primary display.
1297 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1298
1299 // make the GLContext current so that we can create textures when creating
1300 // Layers (which may happens before we render something)
1301 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001302}
1303
Steven Thomasb02664d2017-07-26 18:48:28 -07001304void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1305 hwc2_display_t display, HWC2::Connection connection,
1306 bool primaryDisplay) {
1307 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1308 sequenceId, display,
1309 connection == HWC2::Connection::Connected ?
1310 "connected" : "disconnected",
1311 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001312
Steven Thomasb02664d2017-07-26 18:48:28 -07001313 // Only lock if we're not on the main thread. This function is normally
1314 // called on a hwbinder thread, but for the primary display it's called on
1315 // the main thread with the state lock already held, so don't attempt to
1316 // acquire it here.
1317 ConditionalLock lock(mStateLock,
1318 std::this_thread::get_id() != mMainThreadId);
1319
1320 if (primaryDisplay) {
1321 mHwc->onHotplug(display, connection);
1322 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1323 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001324 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001325 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001326 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001327 if (sequenceId != mComposerSequenceId) {
1328 return;
1329 }
1330 if (mHwc->isUsingVrComposer()) {
1331 ALOGE("External displays are not supported by the vr hardware composer.");
1332 return;
1333 }
1334 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001335 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001336 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001337 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001338 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001339 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1340 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001341 }
1342 setTransactionFlags(eDisplayTransactionNeeded);
1343
Andy McFadden9e9689c2012-10-10 18:17:51 -07001344 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001345 }
Mathias Agopian86303202012-07-24 22:46:10 -07001346}
1347
Steven Thomasb02664d2017-07-26 18:48:28 -07001348void SurfaceFlinger::onRefreshReceived(int sequenceId,
1349 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001350 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001351 if (sequenceId != mComposerSequenceId) {
1352 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001353 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001354 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001355}
1356
Dan Stoza9e56aa02015-11-02 13:00:03 -08001357void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001358 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001360 getHwComposer().setVsyncEnabled(disp,
1361 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001362}
1363
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001364// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001365void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001366 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001367 // Clear the drawing state so that the logic inside of
1368 // handleTransactionLocked will fire. It will determine the delta between
1369 // mCurrentState and mDrawingState and re-apply all changes when we make the
1370 // transition.
1371 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001373 mDisplays.clear();
1374}
1375
Steven Thomas050b2c82017-03-06 11:45:16 -08001376void SurfaceFlinger::updateVrFlinger() {
1377 if (!mVrFlinger)
1378 return;
1379 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1380 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001381 return;
1382 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001383
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1385 ALOGE("Vr flinger is only supported for remote hardware composer"
1386 " service connections. Ignoring request to transition to vr"
1387 " flinger.");
1388 mVrFlingerRequestsDisplay = false;
1389 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001390 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001391
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001392 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001393
Steven Thomasb02664d2017-07-26 18:48:28 -07001394 int currentDisplayPowerMode = getDisplayDeviceLocked(
1395 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001396
Steven Thomasb02664d2017-07-26 18:48:28 -07001397 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001398 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001399 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001400
Steven Thomasb02664d2017-07-26 18:48:28 -07001401 resetDisplayState();
1402 mHwc.reset(); // Delete the current instance before creating the new one
1403 mHwc.reset(new HWComposer(
1404 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1405 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1408 "Switched to non-remote hardware composer");
1409
1410 if (vrFlingerRequestsDisplay) {
1411 mVrFlinger->GrantDisplayOwnership();
1412 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001413 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001414 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001415
1416 mVisibleRegionsDirty = true;
1417 invalidateHwcGeometry();
1418
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001419 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1421 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1422 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001423
Steven Thomasb02664d2017-07-26 18:48:28 -07001424 // Reset the timing values to account for the period of the swapped in HWC
1425 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1426 const nsecs_t period = activeConfig->getVsyncPeriod();
1427 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001428
Steven Thomasb02664d2017-07-26 18:48:28 -07001429 // Use phase of 0 since phase is not known.
1430 // Use latency of 0, which will snap to the ideal latency.
1431 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001432
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001433 android_atomic_or(1, &mRepaintEverything);
1434 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001435}
1436
Mathias Agopian4fec8732012-06-29 14:12:52 -07001437void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001438 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001439 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001440 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001441 bool frameMissed = !mHadClientComposition &&
1442 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001443 (mPreviousPresentFence->getSignalTime() ==
1444 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001445 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001446 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001447 signalLayerUpdate();
1448 break;
1449 }
1450
Steven Thomas050b2c82017-03-06 11:45:16 -08001451 // Now that we're going to make it to the handleMessageTransaction()
1452 // call below it's safe to call updateVrFlinger(), which will
1453 // potentially trigger a display handoff.
1454 updateVrFlinger();
1455
Dan Stoza6b9454d2014-11-07 16:00:59 -08001456 bool refreshNeeded = handleMessageTransaction();
1457 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001458 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001459 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001460 // Signal a refresh if a transaction modified the window state,
1461 // a new buffer was latched, or if HWC has requested a full
1462 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001463 signalRefresh();
1464 }
1465 break;
1466 }
1467 case MessageQueue::REFRESH: {
1468 handleMessageRefresh();
1469 break;
1470 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001471 }
1472}
1473
Dan Stoza6b9454d2014-11-07 16:00:59 -08001474bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001475 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001476 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001477 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001479 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001480 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001481}
1482
Dan Stoza6b9454d2014-11-07 16:00:59 -08001483bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001484 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001485 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001486}
1487
1488void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001489 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001490
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001491 mRefreshPending = false;
1492
Pablo Ceballos40845df2016-01-25 17:41:15 -08001493 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001494
Brian Andersond6927fb2016-07-23 23:37:30 -07001495 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001496 rebuildLayerStacks();
1497 setUpHWComposer();
1498 doDebugFlashRegions();
1499 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001500 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001501
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001502 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001503
1504 mHadClientComposition = false;
1505 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1506 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1507 mHadClientComposition = mHadClientComposition ||
1508 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1509 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001510
Dan Stoza9e56aa02015-11-02 13:00:03 -08001511 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001513
Mathias Agopiancd60f992012-08-16 16:28:27 -07001514void SurfaceFlinger::doDebugFlashRegions()
1515{
1516 // is debugging enabled
1517 if (CC_LIKELY(!mDebugRegion))
1518 return;
1519
1520 const bool repaintEverything = mRepaintEverything;
1521 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1522 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001523 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524 // transform the dirty region into this screen's coordinate space
1525 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1526 if (!dirtyRegion.isEmpty()) {
1527 // redraw the whole screen
1528 doComposeSurfaces(hw, Region(hw->bounds()));
1529
1530 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001531 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001532 RenderEngine& engine(getRenderEngine());
1533 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1534
Mathias Agopianda27af92012-09-13 18:17:13 -07001535 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001536 }
1537 }
1538 }
1539
1540 postFramebuffer();
1541
1542 if (mDebugRegion > 1) {
1543 usleep(mDebugRegion * 1000);
1544 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001545
Dan Stoza9e56aa02015-11-02 13:00:03 -08001546 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001547 auto& displayDevice = mDisplays[displayId];
1548 if (!displayDevice->isDisplayOn()) {
1549 continue;
1550 }
1551
1552 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001553 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1554 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001555 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001556}
1557
Brian Andersond6927fb2016-07-23 23:37:30 -07001558void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001560 ATRACE_CALL();
1561 ALOGV("preComposition");
1562
Mathias Agopiancd60f992012-08-16 16:28:27 -07001563 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001564 mDrawingState.traverseInZOrder([&](Layer* layer) {
1565 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566 needExtraInvalidate = true;
1567 }
Robert Carr2047fae2016-11-28 14:09:09 -08001568 });
1569
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570 if (needExtraInvalidate) {
1571 signalLayerUpdate();
1572 }
1573}
1574
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001575void SurfaceFlinger::updateCompositorTiming(
1576 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1577 std::shared_ptr<FenceTime>& presentFenceTime) {
1578 // Update queue of past composite+present times and determine the
1579 // most recently known composite to present latency.
1580 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1581 nsecs_t compositeToPresentLatency = -1;
1582 while (!mCompositePresentTimes.empty()) {
1583 CompositePresentTime& cpt = mCompositePresentTimes.front();
1584 // Cached values should have been updated before calling this method,
1585 // which helps avoid duplicate syscalls.
1586 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1587 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1588 break;
1589 }
1590 compositeToPresentLatency = displayTime - cpt.composite;
1591 mCompositePresentTimes.pop();
1592 }
1593
1594 // Don't let mCompositePresentTimes grow unbounded, just in case.
1595 while (mCompositePresentTimes.size() > 16) {
1596 mCompositePresentTimes.pop();
1597 }
1598
Brian Andersond0010582017-03-07 13:20:31 -08001599 setCompositorTimingSnapped(
1600 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1601}
1602
1603void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1604 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001605 // Integer division and modulo round toward 0 not -inf, so we need to
1606 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001607 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001608 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1609 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1610
Brian Andersond0010582017-03-07 13:20:31 -08001611 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1612 if (idealLatency <= 0) {
1613 idealLatency = vsyncInterval;
1614 }
1615
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001616 // Snap the latency to a value that removes scheduling jitter from the
1617 // composition and present times, which often have >1ms of jitter.
1618 // Reducing jitter is important if an app attempts to extrapolate
1619 // something (such as user input) to an accurate diasplay time.
1620 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1621 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001622 nsecs_t bias = vsyncInterval / 2;
1623 int64_t extraVsyncs =
1624 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1625 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1626 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001627
Brian Andersond0010582017-03-07 13:20:31 -08001628 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001629 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1630 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001631 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001632}
1633
1634void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001635{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001636 ATRACE_CALL();
1637 ALOGV("postComposition");
1638
Brian Anderson3546a3f2016-07-14 11:51:14 -07001639 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001640 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001641 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001642 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001643 }
1644
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001645 // |mStateLock| not needed as we are on the main thread
1646 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001647
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001648 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001649 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1650 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1651 glCompositionDoneFenceTime =
1652 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1653 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1654 } else {
1655 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1656 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001657
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001658 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001659 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1660 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1661 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001662
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001663 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1664 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1665
1666 // We use the refreshStartTime which might be sampled a little later than
1667 // when we started doing work for this frame, but that should be okay
1668 // since updateCompositorTiming has snapping logic.
1669 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001670 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001671 CompositorTiming compositorTiming;
1672 {
1673 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1674 compositorTiming = mCompositorTiming;
1675 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001676
Robert Carr2047fae2016-11-28 14:09:09 -08001677 mDrawingState.traverseInZOrder([&](Layer* layer) {
1678 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001679 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001680 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001681 recordBufferingStats(layer->getName().string(),
1682 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001683 }
Robert Carr2047fae2016-11-28 14:09:09 -08001684 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001685
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001686 if (presentFenceTime->isValid()) {
1687 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001688 enableHardwareVsync();
1689 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001690 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001691 }
1692 }
1693
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001694 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001695 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001696 enableHardwareVsync();
1697 }
1698 }
1699
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001700 if (mAnimCompositionPending) {
1701 mAnimCompositionPending = false;
1702
Brian Anderson4e606e32017-03-16 15:34:57 -07001703 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001704 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001705 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001706 } else {
1707 // The HWC doesn't support present fences, so use the refresh
1708 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001709 nsecs_t presentTime =
1710 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001711 mAnimFrameTracker.setActualPresentTime(presentTime);
1712 }
1713 mAnimFrameTracker.advanceFrame();
1714 }
Dan Stozab90cf072015-03-05 11:05:59 -08001715
1716 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1717 return;
1718 }
1719
1720 nsecs_t currentTime = systemTime();
1721 if (mHasPoweredOff) {
1722 mHasPoweredOff = false;
1723 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001724 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001725 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001726 if (numPeriods < NUM_BUCKETS - 1) {
1727 mFrameBuckets[numPeriods] += elapsedTime;
1728 } else {
1729 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1730 }
1731 mTotalTime += elapsedTime;
1732 }
1733 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001734}
1735
1736void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001737 ATRACE_CALL();
1738 ALOGV("rebuildLayerStacks");
1739
Mathias Agopiancd60f992012-08-16 16:28:27 -07001740 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001741 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001742 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001743 mVisibleRegionsDirty = false;
1744 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001745
Jeff Sharkey76488112017-02-27 14:15:18 -07001746 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1747 Region opaqueRegion;
1748 Region dirtyRegion;
1749 Vector<sp<Layer>> layersSortedByZ;
1750 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1751 const Transform& tr(displayDevice->getTransform());
1752 const Rect bounds(displayDevice->getBounds());
1753 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001754 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001755
Jeff Sharkey76488112017-02-27 14:15:18 -07001756 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001757 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1758 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001759 Region drawRegion(tr.transform(
1760 layer->visibleNonTransparentRegion));
1761 drawRegion.andSelf(bounds);
1762 if (!drawRegion.isEmpty()) {
1763 layersSortedByZ.add(layer);
1764 } else {
1765 // Clear out the HWC layer if this layer was
1766 // previously visible, but no longer is
Steven Thomasb02664d2017-07-26 18:48:28 -07001767 layer->destroyHwcLayer(
1768 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001769 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001770 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001771 // WM changes displayDevice->layerStack upon sleep/awake.
1772 // Here we make sure we delete the HWC layers even if
1773 // WM changed their layer stack.
Steven Thomasb02664d2017-07-26 18:48:28 -07001774 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001775 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001776 });
1777 }
1778 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1779 displayDevice->undefinedRegion.set(bounds);
1780 displayDevice->undefinedRegion.subtractSelf(
1781 tr.transform(opaqueRegion));
1782 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001783 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001784 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001785}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001786
Romain Guy0147a172017-06-01 13:53:56 -07001787mat4 SurfaceFlinger::computeSaturationMatrix() const {
1788 if (mSaturation == 1.0f) {
1789 return mat4();
1790 }
1791
1792 // Rec.709 luma coefficients
1793 float3 luminance{0.213f, 0.715f, 0.072f};
1794 luminance *= 1.0f - mSaturation;
1795 return mat4(
1796 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1797 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1798 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1799 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1800 );
1801}
1802
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001803// pickColorMode translates a given dataspace into the best available color mode.
1804// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001805android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001806 switch (dataSpace) {
1807 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1808 // system expects.
1809 case HAL_DATASPACE_UNKNOWN:
1810 case HAL_DATASPACE_SRGB:
1811 case HAL_DATASPACE_V0_SRGB:
1812 return HAL_COLOR_MODE_SRGB;
1813 break;
1814
1815 case HAL_DATASPACE_DISPLAY_P3:
1816 return HAL_COLOR_MODE_DISPLAY_P3;
1817 break;
1818
1819 default:
1820 // TODO (courtneygo): Do we want to assert an error here?
1821 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1822 dataSpace);
1823 return HAL_COLOR_MODE_SRGB;
1824 break;
1825 }
1826}
1827
Romain Guy0147a172017-06-01 13:53:56 -07001828android_dataspace SurfaceFlinger::bestTargetDataSpace(
1829 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001830 // Only support sRGB and Display-P3 right now.
1831 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1832 return HAL_DATASPACE_DISPLAY_P3;
1833 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001834 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1835 return HAL_DATASPACE_DISPLAY_P3;
1836 }
1837 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1838 return HAL_DATASPACE_DISPLAY_P3;
1839 }
1840
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001841 return HAL_DATASPACE_V0_SRGB;
1842}
1843
Mathias Agopiancd60f992012-08-16 16:28:27 -07001844void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001845 ATRACE_CALL();
1846 ALOGV("setUpHWComposer");
1847
Jesse Hall028dc8f2013-08-20 16:35:32 -07001848 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001849 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1850 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1851 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1852
1853 // If nothing has changed (!dirty), don't recompose.
1854 // If something changed, but we don't currently have any visible layers,
1855 // and didn't when we last did a composition, then skip it this time.
1856 // The second rule does two things:
1857 // - When all layers are removed from a display, we'll emit one black
1858 // frame, then nothing more until we get new layers.
1859 // - When a display is created with a private layer stack, we won't
1860 // emit any black frames until a layer is added to the layer stack.
1861 bool mustRecompose = dirty && !(empty && wasEmpty);
1862
1863 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1864 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1865 mustRecompose ? "doing" : "skipping",
1866 dirty ? "+" : "-",
1867 empty ? "+" : "-",
1868 wasEmpty ? "+" : "-");
1869
Dan Stoza71433162014-02-04 16:22:36 -08001870 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001871
1872 if (mustRecompose) {
1873 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1874 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001875 }
1876
Dan Stoza9e56aa02015-11-02 13:00:03 -08001877 // build the h/w work list
1878 if (CC_UNLIKELY(mGeometryInvalid)) {
1879 mGeometryInvalid = false;
1880 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1881 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1882 const auto hwcId = displayDevice->getHwcDisplayId();
1883 if (hwcId >= 0) {
1884 const Vector<sp<Layer>>& currentLayers(
1885 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001886 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001887 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001888 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001889 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001890 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001892 }
1893 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001894
Robert Carrae060832016-11-28 10:51:00 -08001895 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001896 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001898 }
1899 }
1900 }
1901 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001902 }
Riley Andrews03414a12014-07-01 14:22:59 -07001903
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001904
Romain Guy0147a172017-06-01 13:53:56 -07001905 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001906
Dan Stoza9e56aa02015-11-02 13:00:03 -08001907 // Set the per-frame data
1908 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1909 auto& displayDevice = mDisplays[displayId];
1910 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001911
Dan Stoza9e56aa02015-11-02 13:00:03 -08001912 if (hwcId < 0) {
1913 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001914 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001915 if (colorMatrix != mPreviousColorMatrix) {
1916 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1917 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1918 "display %zd: %d", displayId, result);
1919 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001920 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1921 layer->setPerFrameData(displayDevice);
1922 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001923
1924 if (hasWideColorDisplay) {
1925 android_color_mode newColorMode;
1926 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1927
1928 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1929 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1930 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1931 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1932 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1933 }
1934 newColorMode = pickColorMode(newDataSpace);
1935
Thierry Strudel2924d012017-08-14 15:19:37 -07001936 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001937 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 }
1939
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001940 mPreviousColorMatrix = colorMatrix;
1941
Dan Stoza9e56aa02015-11-02 13:00:03 -08001942 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001943 auto& displayDevice = mDisplays[displayId];
1944 if (!displayDevice->isDisplayOn()) {
1945 continue;
1946 }
1947
1948 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1950 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001951 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001952}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001953
Mathias Agopiancd60f992012-08-16 16:28:27 -07001954void SurfaceFlinger::doComposition() {
1955 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 ALOGV("doComposition");
1957
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001958 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001959 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001960 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001961 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001962 // transform the dirty region into this screen's coordinate space
1963 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001964
1965 // repaint the framebuffer (if needed)
1966 doDisplayComposition(hw, dirtyRegion);
1967
Mathias Agopiancd60f992012-08-16 16:28:27 -07001968 hw->dirtyRegion.clear();
1969 hw->flip(hw->swapRegion);
1970 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001971 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001972 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001973 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001974}
1975
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001976void SurfaceFlinger::postFramebuffer()
1977{
Mathias Agopian841cde52012-03-01 15:44:37 -08001978 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001979 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001980
Mathias Agopiana44b0412011-10-16 18:46:35 -07001981 const nsecs_t now = systemTime();
1982 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001983
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1985 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001986 if (!displayDevice->isDisplayOn()) {
1987 continue;
1988 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001989 const auto hwcId = displayDevice->getHwcDisplayId();
1990 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001991 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001992 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001993 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001994 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001995 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1996 sp<Fence> releaseFence = Fence::NO_FENCE;
1997 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1998 releaseFence = displayDevice->getClientTargetAcquireFence();
1999 } else {
2000 auto hwcLayer = layer->getHwcLayer(hwcId);
2001 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002002 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 layer->onLayerDisplayed(releaseFence);
2004 }
2005 if (hwcId >= 0) {
2006 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002007 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002008 }
2009
Mathias Agopiana44b0412011-10-16 18:46:35 -07002010 mLastSwapBufferTime = systemTime() - now;
2011 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002012
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002013 // |mStateLock| not needed as we are on the main thread
2014 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002015 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2016 logFrameStats();
2017 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002018}
2019
Mathias Agopian87baae12012-07-31 12:38:26 -07002020void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002021{
Mathias Agopian841cde52012-03-01 15:44:37 -08002022 ATRACE_CALL();
2023
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002024 // here we keep a copy of the drawing state (that is the state that's
2025 // going to be overwritten by handleTransactionLocked()) outside of
2026 // mStateLock so that the side-effects of the State assignment
2027 // don't happen with mStateLock held (which can cause deadlocks).
2028 State drawingState(mDrawingState);
2029
Mathias Agopianca4d3602011-05-19 15:38:14 -07002030 Mutex::Autolock _l(mStateLock);
2031 const nsecs_t now = systemTime();
2032 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002033
Mathias Agopianca4d3602011-05-19 15:38:14 -07002034 // Here we're guaranteed that some transaction flags are set
2035 // so we can call handleTransactionLocked() unconditionally.
2036 // We call getTransactionFlags(), which will also clear the flags,
2037 // with mStateLock held to guarantee that mCurrentState won't change
2038 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002039
Mathias Agopiane57f2922012-08-09 16:29:12 -07002040 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002041 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002042
Mathias Agopianca4d3602011-05-19 15:38:14 -07002043 mLastTransactionTime = systemTime() - now;
2044 mDebugInTransaction = 0;
2045 invalidateHwcGeometry();
2046 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002047}
2048
Mathias Agopian87baae12012-07-31 12:38:26 -07002049void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002050{
Dan Stoza7dde5992015-05-22 09:51:44 -07002051 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002052 mCurrentState.traverseInZOrder([](Layer* layer) {
2053 layer->notifyAvailableFrames();
2054 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002055
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002056 /*
2057 * Traversal of the children
2058 * (perform the transaction for each of them if needed)
2059 */
2060
Mathias Agopian3559b072012-08-15 13:46:03 -07002061 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002062 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002063 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002064 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002065
2066 const uint32_t flags = layer->doTransaction(0);
2067 if (flags & Layer::eVisibleRegion)
2068 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002069 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002070 }
2071
2072 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002073 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002074 */
2075
Mathias Agopiane57f2922012-08-09 16:29:12 -07002076 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002077 // here we take advantage of Vector's copy-on-write semantics to
2078 // improve performance by skipping the transaction entirely when
2079 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002080 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2081 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002082 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002083 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002084 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002085 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002086
2087 // find the displays that were removed
2088 // (ie: in drawing state but not in current state)
2089 // also handle displays that changed
2090 // (ie: displays that are in both lists)
2091 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002092 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2093 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002094 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002095 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002096 // Call makeCurrent() on the primary display so we can
2097 // be sure that nothing associated with this display
2098 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002099 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002100 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002101 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002102 if (hw != NULL)
2103 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002104 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002105 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002106 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002107 } else {
2108 ALOGW("trying to remove the main display");
2109 }
2110 } else {
2111 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002112 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002113 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002114 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2115 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002116 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002117 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002118 // recreating the DisplayDevice, so we just remove it
2119 // from the drawing state, so that it get re-added
2120 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002121 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002122 if (hw != NULL)
2123 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002124 mDisplays.removeItem(display);
2125 mDrawingState.displays.removeItemsAt(i);
2126 dc--; i--;
2127 // at this point we must loop to the next item
2128 continue;
2129 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002130
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002131 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002132 if (disp != NULL) {
2133 if (state.layerStack != draw[i].layerStack) {
2134 disp->setLayerStack(state.layerStack);
2135 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002136 if ((state.orientation != draw[i].orientation)
2137 || (state.viewport != draw[i].viewport)
2138 || (state.frame != draw[i].frame))
2139 {
2140 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002141 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002142 }
Michael Lentine47e45402014-07-18 15:34:25 -07002143 if (state.width != draw[i].width || state.height != draw[i].height) {
2144 disp->setDisplaySize(state.width, state.height);
2145 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002146 }
2147 }
2148 }
2149
2150 // find displays that were added
2151 // (ie: in current state but not in drawing state)
2152 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002153 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002154 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002155
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002156 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002157 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002158 sp<IGraphicBufferProducer> bqProducer;
2159 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002160 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002161
Dan Stoza9e56aa02015-11-02 13:00:03 -08002162 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002163 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002164 // Virtual displays without a surface are dormant:
2165 // they have external state (layer stack, projection,
2166 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002167 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002168
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002169 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002170 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002171 int width = 0;
2172 int status = state.surface->query(
2173 NATIVE_WINDOW_WIDTH, &width);
2174 ALOGE_IF(status != NO_ERROR,
2175 "Unable to query width (%d)", status);
2176 int height = 0;
2177 status = state.surface->query(
2178 NATIVE_WINDOW_HEIGHT, &height);
2179 ALOGE_IF(status != NO_ERROR,
2180 "Unable to query height (%d)", status);
2181 int intFormat = 0;
2182 status = state.surface->query(
2183 NATIVE_WINDOW_FORMAT, &intFormat);
2184 ALOGE_IF(status != NO_ERROR,
2185 "Unable to query format (%d)", status);
2186 auto format = static_cast<android_pixel_format_t>(
2187 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002188
Dan Stoza8cf150a2016-08-02 10:27:31 -07002189 mHwc->allocateVirtualDisplay(width, height, &format,
2190 &hwcId);
2191 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002192
Dan Stoza5cf424b2016-05-20 14:02:39 -07002193 // TODO: Plumb requested format back up to consumer
2194
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 sp<VirtualDisplaySurface> vds =
2196 new VirtualDisplaySurface(*mHwc,
2197 hwcId, state.surface, bqProducer,
2198 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002199
2200 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002201 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002202 }
2203 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002204 ALOGE_IF(state.surface!=NULL,
2205 "adding a supported display, but rendering "
2206 "surface is provided (%p), ignoring it",
2207 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002208
2209 hwcId = state.type;
2210 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2211 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002212 }
2213
2214 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002215 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002216 sp<DisplayDevice> hw =
2217 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2218 dispSurface, producer,
2219 mRenderEngine->getEGLConfig(),
2220 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002221 hw->setLayerStack(state.layerStack);
2222 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002223 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002224 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002225 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002226 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002227 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002228 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002229 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002230 }
2231 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002232 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002233 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234
Mathias Agopian84300952012-11-21 16:02:13 -08002235 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2236 // The transform hint might have changed for some layers
2237 // (either because a display has changed, or because a layer
2238 // as changed).
2239 //
2240 // Walk through all the layers in currentLayers,
2241 // and update their transform hint.
2242 //
2243 // If a layer is visible only on a single display, then that
2244 // display is used to calculate the hint, otherwise we use the
2245 // default display.
2246 //
2247 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2248 // the hint is set before we acquire a buffer from the surface texture.
2249 //
2250 // NOTE: layer transactions have taken place already, so we use their
2251 // drawing state. However, SurfaceFlinger's own transaction has not
2252 // happened yet, so we must use the current state layer list
2253 // (soon to become the drawing state list).
2254 //
2255 sp<const DisplayDevice> disp;
2256 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002257 bool first = true;
2258 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002259 // NOTE: we rely on the fact that layers are sorted by
2260 // layerStack first (so we don't have to traverse the list
2261 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002262 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002263 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002264 currentlayerStack = layerStack;
2265 // figure out if this layerstack is mirrored
2266 // (more than one display) if so, pick the default display,
2267 // if not, pick the only display it's on.
2268 disp.clear();
2269 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2270 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002271 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002272 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002273 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002274 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002275 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002276 break;
2277 }
2278 }
2279 }
2280 }
Chet Haase91d25932013-04-11 15:24:55 -07002281 if (disp == NULL) {
2282 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2283 // redraw after transform hint changes. See bug 8508397.
2284
2285 // could be null when this layer is using a layerStack
2286 // that is not visible on any display. Also can occur at
2287 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002288 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002289 }
Chet Haase91d25932013-04-11 15:24:55 -07002290 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002291
2292 first = false;
2293 });
Mathias Agopian84300952012-11-21 16:02:13 -08002294 }
2295
2296
Mathias Agopian3559b072012-08-15 13:46:03 -07002297 /*
2298 * Perform our own transaction if needed
2299 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002300
2301 if (mLayersAdded) {
2302 mLayersAdded = false;
2303 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002304 mVisibleRegionsDirty = true;
2305 }
2306
2307 // some layers might have been removed, so
2308 // we need to update the regions they're exposing.
2309 if (mLayersRemoved) {
2310 mLayersRemoved = false;
2311 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002312 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002313 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002314 // this layer is not visible anymore
2315 // TODO: we could traverse the tree from front to back and
2316 // compute the actual visible region
2317 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002318 Region visibleReg;
2319 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002320 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002321 }
Robert Carr2047fae2016-11-28 14:09:09 -08002322 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002323 }
2324
2325 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002326
2327 updateCursorAsync();
2328}
2329
2330void SurfaceFlinger::updateCursorAsync()
2331{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002332 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2333 auto& displayDevice = mDisplays[displayId];
2334 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002335 continue;
2336 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002337
2338 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2339 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002340 }
2341 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002342}
2343
2344void SurfaceFlinger::commitTransaction()
2345{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002346 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002347 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002348 for (const auto& l : mLayersPendingRemoval) {
2349 recordBufferingStats(l->getName().string(),
2350 l->getOccupancyHistory(true));
2351 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002352 }
2353 mLayersPendingRemoval.clear();
2354 }
2355
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002356 // If this transaction is part of a window animation then the next frame
2357 // we composite should be considered an animation as well.
2358 mAnimCompositionPending = mAnimTransactionPending;
2359
Mathias Agopian4fec8732012-06-29 14:12:52 -07002360 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002361 mDrawingState.traverseInZOrder([](Layer* layer) {
2362 layer->commitChildList();
2363 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002364 mTransactionPending = false;
2365 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002366 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367}
2368
Chia-I Wuab0c3192017-08-01 11:29:00 -07002369void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002370 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002371{
Mathias Agopian841cde52012-03-01 15:44:37 -08002372 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002373 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002374
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002375 Region aboveOpaqueLayers;
2376 Region aboveCoveredLayers;
2377 Region dirty;
2378
Mathias Agopian87baae12012-07-31 12:38:26 -07002379 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002380
Robert Carr2047fae2016-11-28 14:09:09 -08002381 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002382 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002383 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384
Jesse Hall01e29052013-02-19 16:13:35 -08002385 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002386 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002387 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002388
Mathias Agopianab028732010-03-16 16:41:46 -07002389 /*
2390 * opaqueRegion: area of a surface that is fully opaque.
2391 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002393
2394 /*
2395 * visibleRegion: area of a surface that is visible on screen
2396 * and not fully transparent. This is essentially the layer's
2397 * footprint minus the opaque regions above it.
2398 * Areas covered by a translucent surface are considered visible.
2399 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002400 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002401
2402 /*
2403 * coveredRegion: area of a surface that is covered by all
2404 * visible regions above it (which includes the translucent areas).
2405 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002406 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002407
Jesse Halla8026d22012-09-25 13:25:04 -07002408 /*
2409 * transparentRegion: area of a surface that is hinted to be completely
2410 * transparent. This is only used to tell when the layer has no visible
2411 * non-transparent regions and can be removed from the layer list. It
2412 * does not affect the visibleRegion of this layer or any layers
2413 * beneath it. The hint may not be correct if apps don't respect the
2414 * SurfaceView restrictions (which, sadly, some don't).
2415 */
2416 Region transparentRegion;
2417
Mathias Agopianab028732010-03-16 16:41:46 -07002418
2419 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002420 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002421 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002422 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002423 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002424 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002425 if (!visibleRegion.isEmpty()) {
2426 // Remove the transparent area from the visible region
2427 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002428 if (tr.preserveRects()) {
2429 // transform the transparent region
2430 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002431 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002432 // transformation too complex, can't do the
2433 // transparent region optimization.
2434 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002435 }
Mathias Agopianab028732010-03-16 16:41:46 -07002436 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002437
Mathias Agopianab028732010-03-16 16:41:46 -07002438 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002439 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002440 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002441 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2442 // the opaque region is the layer's footprint
2443 opaqueRegion = visibleRegion;
2444 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445 }
2446 }
2447
Mathias Agopianab028732010-03-16 16:41:46 -07002448 // Clip the covered region to the visible region
2449 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2450
2451 // Update aboveCoveredLayers for next (lower) layer
2452 aboveCoveredLayers.orSelf(visibleRegion);
2453
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454 // subtract the opaque region covered by the layers above us
2455 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456
2457 // compute this layer's dirty region
2458 if (layer->contentDirty) {
2459 // we need to invalidate the whole region
2460 dirty = visibleRegion;
2461 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002462 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463 layer->contentDirty = false;
2464 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002465 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002466 * the exposed region consists of two components:
2467 * 1) what's VISIBLE now and was COVERED before
2468 * 2) what's EXPOSED now less what was EXPOSED before
2469 *
2470 * note that (1) is conservative, we start with the whole
2471 * visible region but only keep what used to be covered by
2472 * something -- which mean it may have been exposed.
2473 *
2474 * (2) handles areas that were not covered by anything but got
2475 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002476 */
Mathias Agopianab028732010-03-16 16:41:46 -07002477 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002478 const Region oldVisibleRegion = layer->visibleRegion;
2479 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002480 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2481 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482 }
2483 dirty.subtractSelf(aboveOpaqueLayers);
2484
2485 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002486 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487
Mathias Agopianab028732010-03-16 16:41:46 -07002488 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002490
Jesse Halla8026d22012-09-25 13:25:04 -07002491 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492 layer->setVisibleRegion(visibleRegion);
2493 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002494 layer->setVisibleNonTransparentRegion(
2495 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002496 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497
Mathias Agopian87baae12012-07-31 12:38:26 -07002498 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499}
2500
Chia-I Wuab0c3192017-08-01 11:29:00 -07002501void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002502 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002503 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002504 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002505 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002506 }
2507 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002508}
2509
Dan Stoza6b9454d2014-11-07 16:00:59 -08002510bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002512 ALOGV("handlePageFlip");
2513
Brian Andersond6927fb2016-07-23 23:37:30 -07002514 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515
Mathias Agopian4fec8732012-06-29 14:12:52 -07002516 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002517 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002518 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002519
2520 // Store the set of layers that need updates. This set must not change as
2521 // buffers are being latched, as this could result in a deadlock.
2522 // Example: Two producers share the same command stream and:
2523 // 1.) Layer 0 is latched
2524 // 2.) Layer 0 gets a new frame
2525 // 2.) Layer 1 gets a new frame
2526 // 3.) Layer 1 is latched.
2527 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2528 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002529 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002530 if (layer->hasQueuedFrame()) {
2531 frameQueued = true;
2532 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002533 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002534 } else {
2535 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002536 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002537 } else {
2538 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002539 }
Robert Carr2047fae2016-11-28 14:09:09 -08002540 });
2541
Dan Stoza9e56aa02015-11-02 13:00:03 -08002542 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002543 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002544 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002545 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002546 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002547 newDataLatched = true;
2548 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002549 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002550
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002551 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002552
2553 // If we will need to wake up at some time in the future to deal with a
2554 // queued frame that shouldn't be displayed during this vsync period, wake
2555 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002556 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002557 signalLayerUpdate();
2558 }
2559
2560 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002561 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562}
2563
Mathias Agopianad456f92011-01-13 17:53:01 -08002564void SurfaceFlinger::invalidateHwcGeometry()
2565{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002566 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002567}
2568
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002569
Fabien Sanglard830b8472016-11-30 16:35:58 -08002570void SurfaceFlinger::doDisplayComposition(
2571 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002572 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573{
Dan Stoza71433162014-02-04 16:22:36 -08002574 // We only need to actually compose the display if:
2575 // 1) It is being handled by hardware composer, which may need this to
2576 // keep its virtual display state machine in sync, or
2577 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002578 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002579 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002580 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002581 return;
2582 }
2583
Dan Stoza9e56aa02015-11-02 13:00:03 -08002584 ALOGV("doDisplayComposition");
2585
Mathias Agopian87baae12012-07-31 12:38:26 -07002586 Region dirtyRegion(inDirtyRegion);
2587
Mathias Agopianb8a55602009-06-26 19:06:36 -07002588 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002589 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590
Fabien Sanglard830b8472016-11-30 16:35:58 -08002591 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002592 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002593 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2594 // takes a rectangle, we must make sure to update that whole
2595 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002596 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002597 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002598 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002599 // We need to redraw the rectangle that will be updated
2600 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002601 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002602 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002603 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002604 } else {
2605 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002606 dirtyRegion.set(displayDevice->bounds());
2607 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608 }
2609 }
2610
Fabien Sanglard830b8472016-11-30 16:35:58 -08002611 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002613 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002614 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002615
2616 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002617 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618}
2619
Dan Stoza9e56aa02015-11-02 13:00:03 -08002620bool SurfaceFlinger::doComposeSurfaces(
2621 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002622{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002623 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002624
Dan Stoza9e56aa02015-11-02 13:00:03 -08002625 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002626
2627 mat4 oldColorMatrix;
2628 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2629 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2630 if (applyColorMatrix) {
2631 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2632 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2633 }
2634
Dan Stoza9e56aa02015-11-02 13:00:03 -08002635 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2636 if (hasClientComposition) {
2637 ALOGV("hasClientComposition");
2638
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002639#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002640 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002641 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002642#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002643 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002644 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002645 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002646 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002647
2648 // |mStateLock| not needed as we are on the main thread
2649 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002650 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2651 }
2652 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002653 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002654
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002655 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002656 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2657 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002658 // when using overlays, we assume a fully transparent framebuffer
2659 // NOTE: we could reduce how much we need to clear, for instance
2660 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002661 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002662 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002664 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002665 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002666 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002667
2668 // we remove the scissor part
2669 // we're left with the letterbox region
2670 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002672
2673 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002674 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002675
2676 // but limit it to the dirty region
2677 region.andSelf(dirty);
2678
Mathias Agopianb9494d52012-04-18 02:28:45 -07002679 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002680 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002681 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002682 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002683 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002684 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002685
Dan Stoza9e56aa02015-11-02 13:00:03 -08002686 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002687 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002688 // scissor on the main display. It should never be needed
2689 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002690 const Rect& bounds(displayDevice->getBounds());
2691 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002692 if (scissor != bounds) {
2693 // scissor doesn't match the screen's dimensions, so we
2694 // need to clear everything outside of it and enable
2695 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002696
Mathias Agopianf45c5102012-10-24 16:29:17 -07002697 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002698 const uint32_t height = displayDevice->getHeight();
2699 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002700 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002701 }
2702 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002703 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002704
Mathias Agopian85d751c2012-08-29 16:59:24 -07002705 /*
2706 * and then, render the layers targeted at the framebuffer
2707 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002708
Dan Stoza9e56aa02015-11-02 13:00:03 -08002709 ALOGV("Rendering client layers");
2710 const Transform& displayTransform = displayDevice->getTransform();
2711 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002712 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002713 bool firstLayer = true;
2714 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2715 const Region clip(dirty.intersect(
2716 displayTransform.transform(layer->visibleRegion)));
2717 ALOGV("Layer: %s", layer->getName().string());
2718 ALOGV(" Composition type: %s",
2719 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002720 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002721 switch (layer->getCompositionType(hwcId)) {
2722 case HWC2::Composition::Cursor:
2723 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002724 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002725 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002726 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002727 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2728 layer->isOpaque(state) && (state.alpha == 1.0f)
2729 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002730 // never clear the very first layer since we're
2731 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002732 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002733 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002734 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002735 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002736 case HWC2::Composition::Client: {
2737 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002738 break;
2739 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002741 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002742 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002743 } else {
2744 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002745 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002746 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002747 }
2748 } else {
2749 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002750 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002751 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002753 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002754 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002755 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002756 }
2757 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002758
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002759 if (applyColorMatrix) {
2760 getRenderEngine().setupColorTransform(oldColorMatrix);
2761 }
2762
Mathias Agopianf45c5102012-10-24 16:29:17 -07002763 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002764 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002765 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766}
2767
Fabien Sanglard830b8472016-11-30 16:35:58 -08002768void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2769 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002770 RenderEngine& engine(getRenderEngine());
2771 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772}
2773
Dan Stoza7d89d062015-04-30 13:29:25 -07002774status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002775 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002776 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002777 const sp<Layer>& lbc,
2778 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002779{
Dan Stoza7d89d062015-04-30 13:29:25 -07002780 // add this layer to the current state list
2781 {
2782 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002783 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002784 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2785 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002786 return NO_MEMORY;
2787 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002788 if (parent == nullptr) {
2789 mCurrentState.layersSortedByZ.add(lbc);
2790 } else {
chaviwc9674332017-08-28 12:32:18 -07002791 bool found = false;
2792 mCurrentState.traverseInZOrder([&](Layer* layer) {
2793 if (layer == parent.get()) {
2794 found = true;
2795 }
2796 });
2797
2798 if (!found) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002799 ALOGE("addClientLayer called with a removed parent");
2800 return NAME_NOT_FOUND;
2801 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002802 parent->addChild(lbc);
2803 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002804
Dan Stoza7d89d062015-04-30 13:29:25 -07002805 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002806 mLayersAdded = true;
2807 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002808 }
2809
Mathias Agopian96f08192010-06-02 23:28:45 -07002810 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002811 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002812
Dan Stoza7d89d062015-04-30 13:29:25 -07002813 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002814}
2815
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002816status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002817 Mutex::Autolock _l(mStateLock);
2818
Robert Carr1f0a16a2016-10-24 16:27:39 -07002819 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002820 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002821 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002822 if (topLevelOnly) {
2823 return NO_ERROR;
2824 }
2825
Chia-I Wu98f1c102017-05-30 14:54:08 -07002826 sp<Layer> ancestor = p;
2827 while (ancestor->getParent() != nullptr) {
2828 ancestor = ancestor->getParent();
2829 }
2830 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2831 ALOGE("removeLayer called with a layer whose parent has been removed");
2832 return NAME_NOT_FOUND;
2833 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002834
2835 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002836 } else {
2837 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002838 }
2839
Robert Carr136e2f62017-02-08 17:54:29 -08002840 // As a matter of normal operation, the LayerCleaner will produce a second
2841 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2842 // so we will succeed in promoting it, but it's already been removed
2843 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2844 // otherwise something has gone wrong and we are leaking the layer.
2845 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002846 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2847 layer->getName().string(),
2848 (p != nullptr) ? p->getName().string() : "no-parent");
2849 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002850 } else if (index < 0) {
2851 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002852 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002853
Chia-I Wuc6657022017-08-15 11:18:17 -07002854 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002855 mLayersPendingRemoval.add(layer);
2856 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002857 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002858 setTransactionFlags(eTransactionNeeded);
2859 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860}
2861
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002862uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002863 return android_atomic_release_load(&mTransactionFlags);
2864}
2865
Mathias Agopian3f844832013-08-07 21:24:32 -07002866uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2868}
2869
Mathias Agopian3f844832013-08-07 21:24:32 -07002870uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2872 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002873 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 }
2875 return old;
2876}
2877
Mathias Agopian8b33f032012-07-24 20:43:54 -07002878void SurfaceFlinger::setTransactionState(
2879 const Vector<ComposerState>& state,
2880 const Vector<DisplayState>& displays,
2881 uint32_t flags)
2882{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002883 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002884 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002885 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002886
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002887 if (flags & eAnimation) {
2888 // For window updates that are part of an animation we must wait for
2889 // previous animation "frames" to be handled.
2890 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002891 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002892 if (CC_UNLIKELY(err != NO_ERROR)) {
2893 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002894 // caller after a few seconds.
2895 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2896 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002897 mAnimTransactionPending = false;
2898 break;
2899 }
2900 }
2901 }
2902
Mathias Agopiane57f2922012-08-09 16:29:12 -07002903 size_t count = displays.size();
2904 for (size_t i=0 ; i<count ; i++) {
2905 const DisplayState& s(displays[i]);
2906 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002907 }
2908
Mathias Agopiane57f2922012-08-09 16:29:12 -07002909 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002910 for (size_t i=0 ; i<count ; i++) {
2911 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002912 // Here we need to check that the interface we're given is indeed
2913 // one of our own. A malicious client could give us a NULL
2914 // IInterface, or one of its own or even one of our own but a
2915 // different type. All these situations would cause us to crash.
2916 //
2917 // NOTE: it would be better to use RTTI as we could directly check
2918 // that we have a Client*. however, RTTI is disabled in Android.
2919 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002920 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002921 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002922 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002923 sp<Client> client( static_cast<Client *>(s.client.get()) );
2924 transactionFlags |= setClientStateLocked(client, s.state);
2925 }
2926 }
2927 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002928 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002929
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002930 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2931 // anyway. This can be used as a flush mechanism for previous async transactions.
2932 // Empty animation transaction can be used to simulate back-pressure, so also force a
2933 // transaction for empty animation transactions.
2934 if (transactionFlags == 0 &&
2935 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002936 transactionFlags = eTransactionNeeded;
2937 }
2938
Mathias Agopian386aa982011-11-07 21:58:03 -08002939 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002940 if (mInterceptor.isEnabled()) {
2941 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2942 }
Irvel468051e2016-06-13 16:44:44 -07002943
Mathias Agopian386aa982011-11-07 21:58:03 -08002944 // this triggers the transaction
2945 setTransactionFlags(transactionFlags);
2946
2947 // if this is a synchronous transaction, wait for it to take effect
2948 // before returning.
2949 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002950 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002951 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002952 if (flags & eAnimation) {
2953 mAnimTransactionPending = true;
2954 }
2955 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002956 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2957 if (CC_UNLIKELY(err != NO_ERROR)) {
2958 // just in case something goes wrong in SF, return to the
2959 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002960 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2961 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002962 break;
2963 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002964 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002965 }
2966}
2967
Mathias Agopiane57f2922012-08-09 16:29:12 -07002968uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2969{
Jesse Hall9a143922012-10-04 16:29:19 -07002970 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2971 if (dpyIdx < 0)
2972 return 0;
2973
Mathias Agopiane57f2922012-08-09 16:29:12 -07002974 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002975 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002976 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002977 const uint32_t what = s.what;
2978 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002979 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002980 disp.surface = s.surface;
2981 flags |= eDisplayTransactionNeeded;
2982 }
2983 }
2984 if (what & DisplayState::eLayerStackChanged) {
2985 if (disp.layerStack != s.layerStack) {
2986 disp.layerStack = s.layerStack;
2987 flags |= eDisplayTransactionNeeded;
2988 }
2989 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002990 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002991 if (disp.orientation != s.orientation) {
2992 disp.orientation = s.orientation;
2993 flags |= eDisplayTransactionNeeded;
2994 }
2995 if (disp.frame != s.frame) {
2996 disp.frame = s.frame;
2997 flags |= eDisplayTransactionNeeded;
2998 }
2999 if (disp.viewport != s.viewport) {
3000 disp.viewport = s.viewport;
3001 flags |= eDisplayTransactionNeeded;
3002 }
3003 }
Michael Lentine47e45402014-07-18 15:34:25 -07003004 if (what & DisplayState::eDisplaySizeChanged) {
3005 if (disp.width != s.width) {
3006 disp.width = s.width;
3007 flags |= eDisplayTransactionNeeded;
3008 }
3009 if (disp.height != s.height) {
3010 disp.height = s.height;
3011 flags |= eDisplayTransactionNeeded;
3012 }
3013 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003014 }
3015 return flags;
3016}
3017
3018uint32_t SurfaceFlinger::setClientStateLocked(
3019 const sp<Client>& client,
3020 const layer_state_t& s)
3021{
3022 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003023 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003024 if (layer != 0) {
3025 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003026 bool geometryAppliesWithResize =
3027 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003028 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003029 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003030 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003031 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003032 }
3033 if (what & layer_state_t::eLayerChanged) {
3034 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003035 const auto& p = layer->getParent();
3036 if (p == nullptr) {
3037 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3038 if (layer->setLayer(s.z) && idx >= 0) {
3039 mCurrentState.layersSortedByZ.removeAt(idx);
3040 mCurrentState.layersSortedByZ.add(layer);
3041 // we need traversal (state changed)
3042 // AND transaction (list changed)
3043 flags |= eTransactionNeeded|eTraversalNeeded;
3044 }
3045 } else {
3046 if (p->setChildLayer(layer, s.z)) {
3047 flags |= eTransactionNeeded|eTraversalNeeded;
3048 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003049 }
3050 }
Robert Carrdb66e622017-04-10 16:55:57 -07003051 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003052 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003053 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003054 mCurrentState.layersSortedByZ.removeAt(idx);
3055 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003056 flags |= eTransactionNeeded|eTraversalNeeded;
3057 }
3058 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003059 if (what & layer_state_t::eSizeChanged) {
3060 if (layer->setSize(s.w, s.h)) {
3061 flags |= eTraversalNeeded;
3062 }
3063 }
3064 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003065 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003066 flags |= eTraversalNeeded;
3067 }
3068 if (what & layer_state_t::eMatrixChanged) {
3069 if (layer->setMatrix(s.matrix))
3070 flags |= eTraversalNeeded;
3071 }
3072 if (what & layer_state_t::eTransparentRegionChanged) {
3073 if (layer->setTransparentRegionHint(s.transparentRegion))
3074 flags |= eTraversalNeeded;
3075 }
Dan Stoza23116082015-06-18 14:58:39 -07003076 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003077 if (layer->setFlags(s.flags, s.mask))
3078 flags |= eTraversalNeeded;
3079 }
3080 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003081 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003082 flags |= eTraversalNeeded;
3083 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003084 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003085 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003086 flags |= eTraversalNeeded;
3087 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003088 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003089 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003090 // We only allow setting layer stacks for top level layers,
3091 // everything else inherits layer stack from its parent.
3092 if (layer->hasParent()) {
3093 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3094 layer->getName().string());
3095 } else if (idx < 0) {
3096 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3097 "that also does not appear in the top level layer list. Something"
3098 " has gone wrong.", layer->getName().string());
3099 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003100 mCurrentState.layersSortedByZ.removeAt(idx);
3101 mCurrentState.layersSortedByZ.add(layer);
3102 // we need traversal (state changed)
3103 // AND transaction (list changed)
3104 flags |= eTransactionNeeded|eTraversalNeeded;
3105 }
3106 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003107 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003108 if (s.barrierHandle != nullptr) {
3109 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3110 } else if (s.barrierGbp != nullptr) {
3111 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3112 if (authenticateSurfaceTextureLocked(gbp)) {
3113 const auto& otherLayer =
3114 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3115 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3116 } else {
3117 ALOGE("Attempt to defer transaction to to an"
3118 " unrecognized GraphicBufferProducer");
3119 }
3120 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003121 // We don't trigger a traversal here because if no other state is
3122 // changed, we don't want this to cause any more work
3123 }
chaviw06178942017-07-27 10:25:59 -07003124 // Always re-parent the children that explicitly requested to get
3125 // re-parented before the general re-parent of all children.
3126 if (what & layer_state_t::eReparentChild) {
3127 if (layer->reparentChild(s.parentHandleForChild, s.childHandle)) {
3128 flags |= eTransactionNeeded|eTraversalNeeded;
3129 }
3130 }
Robert Carr1db73f62016-12-21 12:58:51 -08003131 if (what & layer_state_t::eReparentChildren) {
3132 if (layer->reparentChildren(s.reparentHandle)) {
3133 flags |= eTransactionNeeded|eTraversalNeeded;
3134 }
3135 }
Robert Carr9524cb32017-02-13 11:32:32 -08003136 if (what & layer_state_t::eDetachChildren) {
3137 layer->detachChildren();
3138 }
Robert Carrc3574f72016-03-24 12:19:32 -07003139 if (what & layer_state_t::eOverrideScalingModeChanged) {
3140 layer->setOverrideScalingMode(s.overrideScalingMode);
3141 // We don't trigger a traversal here because if no other state is
3142 // changed, we don't want this to cause any more work
3143 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003144 }
3145 return flags;
3146}
3147
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003148status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003149 const String8& name,
3150 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003151 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003152 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3153 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003155 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003156 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003157 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003158 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003159 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003160
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003161 status_t result = NO_ERROR;
3162
3163 sp<Layer> layer;
3164
Cody Northropbc755282017-03-31 12:00:08 -06003165 String8 uniqueName = getUniqueLayerName(name);
3166
Mathias Agopian3165cc22012-08-08 19:42:09 -07003167 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3168 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003169 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003170 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003171 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003173 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003174 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003175 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003176 handle, gbp, &layer);
3177 break;
3178 default:
3179 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180 break;
3181 }
3182
Dan Stoza7d89d062015-04-30 13:29:25 -07003183 if (result != NO_ERROR) {
3184 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003185 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003186
Chia-I Wuab0c3192017-08-01 11:29:00 -07003187 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3188 // TODO b/64227542
3189 if (windowType == 441731) {
3190 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3191 layer->setPrimaryDisplayOnly();
3192 }
3193
Albert Chaulk479c60c2017-01-27 14:21:34 -05003194 layer->setInfo(windowType, ownerUid);
3195
Robert Carr1f0a16a2016-10-24 16:27:39 -07003196 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003197 if (result != NO_ERROR) {
3198 return result;
3199 }
Irvelffc9efc2016-07-27 15:16:37 -07003200 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003201
3202 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003203 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204}
3205
Cody Northropbc755282017-03-31 12:00:08 -06003206String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3207{
3208 bool matchFound = true;
3209 uint32_t dupeCounter = 0;
3210
3211 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3212 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3213
3214 // Loop over layers until we're sure there is no matching name
3215 while (matchFound) {
3216 matchFound = false;
3217 mDrawingState.traverseInZOrder([&](Layer* layer) {
3218 if (layer->getName() == uniqueName) {
3219 matchFound = true;
3220 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3221 }
3222 });
3223 }
3224
3225 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3226
3227 return uniqueName;
3228}
3229
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003230status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3231 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3232 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233{
3234 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003235 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236 case PIXEL_FORMAT_TRANSPARENT:
3237 case PIXEL_FORMAT_TRANSLUCENT:
3238 format = PIXEL_FORMAT_RGBA_8888;
3239 break;
3240 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003241 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242 break;
3243 }
3244
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003245 *outLayer = new Layer(this, client, name, w, h, flags);
3246 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3247 if (err == NO_ERROR) {
3248 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003249 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003250 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003251
3252 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3253 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003254}
3255
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003256status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3257 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3258 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003259{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003260 *outLayer = new LayerDim(this, client, name, w, h, flags);
3261 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003262 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003263 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003264}
3265
Mathias Agopianac9fa422013-02-11 16:40:36 -08003266status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267{
Robert Carr9524cb32017-02-13 11:32:32 -08003268 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003269 status_t err = NO_ERROR;
3270 sp<Layer> l(client->getLayerUser(handle));
3271 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003272 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003273 err = removeLayer(l);
3274 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3275 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003276 }
3277 return err;
3278}
3279
Mathias Agopian13127d82013-03-05 17:47:11 -08003280status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003281{
Mathias Agopian67106042013-03-14 19:18:13 -07003282 // called by ~LayerCleaner() when all references to the IBinder (handle)
3283 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003284 sp<Layer> l = layer.promote();
3285 if (l == nullptr) {
3286 // The layer has already been removed, carry on
3287 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003288 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003289 // If we have a parent, then we can continue to live as long as it does.
3290 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291}
3292
Mathias Agopianb60314a2012-04-10 22:09:54 -07003293// ---------------------------------------------------------------------------
3294
Andy McFadden13a082e2012-08-24 10:16:42 -07003295void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003296 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003297 Vector<ComposerState> state;
3298 Vector<DisplayState> displays;
3299 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003300 d.what = DisplayState::eDisplayProjectionChanged |
3301 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003302 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003303 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003304 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003305 d.frame.makeInvalid();
3306 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003307 d.width = 0;
3308 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003309 displays.add(d);
3310 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003311 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3312 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003313
Dan Stoza9e56aa02015-11-02 13:00:03 -08003314 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3315 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003316 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003317
Brian Andersond0010582017-03-07 13:20:31 -08003318 // Use phase of 0 since phase is not known.
3319 // Use latency of 0, which will snap to the ideal latency.
3320 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003321}
3322
3323void SurfaceFlinger::initializeDisplays() {
3324 class MessageScreenInitialized : public MessageBase {
3325 SurfaceFlinger* flinger;
3326 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003327 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003328 virtual bool handler() {
3329 flinger->onInitializeDisplays();
3330 return true;
3331 }
3332 };
3333 sp<MessageBase> msg = new MessageScreenInitialized(this);
3334 postMessageAsync(msg); // we may be called from main thread, use async message
3335}
3336
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003337void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003338 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003339 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3340 this);
3341 int32_t type = hw->getDisplayType();
3342 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003343
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003344 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003345 return;
3346 }
3347
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003348 hw->setPowerMode(mode);
3349 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3350 ALOGW("Trying to set power mode for virtual display");
3351 return;
3352 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003353
Irvelffc9efc2016-07-27 15:16:37 -07003354 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003355 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003356 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3357 if (idx < 0) {
3358 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3359 return;
3360 }
3361 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3362 }
3363
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003364 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003365 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003366 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003367 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3368 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003369 // FIXME: eventthread only knows about the main display right now
3370 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003371 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003372 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003373
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003374 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003375 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003376 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003377
3378 struct sched_param param = {0};
3379 param.sched_priority = 1;
3380 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3381 ALOGW("Couldn't set SCHED_FIFO on display on");
3382 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003383 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003384 // Turn off the display
3385 struct sched_param param = {0};
3386 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3387 ALOGW("Couldn't set SCHED_OTHER on display off");
3388 }
3389
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003390 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003391 disableHardwareVsync(true); // also cancels any in-progress resync
3392
Mathias Agopiancde87a32012-09-13 14:09:01 -07003393 // FIXME: eventthread only knows about the main display right now
3394 mEventThread->onScreenReleased();
3395 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003396
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003397 getHwComposer().setPowerMode(type, mode);
3398 mVisibleRegionsDirty = true;
3399 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003400 } else if (mode == HWC_POWER_MODE_DOZE ||
3401 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003402 // Update display while dozing
3403 getHwComposer().setPowerMode(type, mode);
3404 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3405 // FIXME: eventthread only knows about the main display right now
3406 mEventThread->onScreenAcquired();
3407 resyncToHardwareVsync(true);
3408 }
3409 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3410 // Leave display going to doze
3411 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3412 disableHardwareVsync(true); // also cancels any in-progress resync
3413 // FIXME: eventthread only knows about the main display right now
3414 mEventThread->onScreenReleased();
3415 }
3416 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003417 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003418 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003419 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003420 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003421}
3422
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003423void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3424 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003425 SurfaceFlinger& mFlinger;
3426 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003427 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003428 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003429 MessageSetPowerMode(SurfaceFlinger& flinger,
3430 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3431 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003432 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003433 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003434 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003435 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003436 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003437 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003438 ALOGW("Attempt to set power mode = %d for virtual display",
3439 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003440 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003441 mFlinger.setPowerModeInternal(
3442 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003443 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003444 return true;
3445 }
3446 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003447 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003448 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003449}
3450
3451// ---------------------------------------------------------------------------
3452
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003453status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3454{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003455 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003456
Mathias Agopianbd115332013-04-18 16:41:04 -07003457 IPCThreadState* ipc = IPCThreadState::self();
3458 const int pid = ipc->getCallingPid();
3459 const int uid = ipc->getCallingUid();
3460 if ((uid != AID_SHELL) &&
3461 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003462 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003463 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003464 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003465 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003466 // (this would indicate SF is stuck, but we want to be able to
3467 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003468 status_t err = mStateLock.timedLock(s2ns(1));
3469 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003470 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003471 result.appendFormat(
3472 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3473 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003474 }
3475
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003476 bool dumpAll = true;
3477 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003478 size_t numArgs = args.size();
3479 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003480 if ((index < numArgs) &&
3481 (args[index] == String16("--list"))) {
3482 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003483 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003484 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003485 }
3486
3487 if ((index < numArgs) &&
3488 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003489 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003490 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003491 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003492 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003493
3494 if ((index < numArgs) &&
3495 (args[index] == String16("--latency-clear"))) {
3496 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003497 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003498 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003499 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003500
3501 if ((index < numArgs) &&
3502 (args[index] == String16("--dispsync"))) {
3503 index++;
3504 mPrimaryDispSync.dump(result);
3505 dumpAll = false;
3506 }
Dan Stozab90cf072015-03-05 11:05:59 -08003507
3508 if ((index < numArgs) &&
3509 (args[index] == String16("--static-screen"))) {
3510 index++;
3511 dumpStaticScreenStats(result);
3512 dumpAll = false;
3513 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003514
3515 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003516 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003517 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003518 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003519 dumpAll = false;
3520 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003521
3522 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3523 index++;
3524 dumpWideColorInfo(result);
3525 dumpAll = false;
3526 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003528
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003529 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003530 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003531 }
3532
Mathias Agopian9795c422009-08-26 16:36:26 -07003533 if (locked) {
3534 mStateLock.unlock();
3535 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003536 }
3537 write(fd, result.string(), result.size());
3538 return NO_ERROR;
3539}
3540
Dan Stozac7014012014-02-14 15:03:43 -08003541void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3542 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003543{
Robert Carr2047fae2016-11-28 14:09:09 -08003544 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003545 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003546 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003547}
3548
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003549void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003550 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003551{
3552 String8 name;
3553 if (index < args.size()) {
3554 name = String8(args[index]);
3555 index++;
3556 }
3557
Dan Stoza9e56aa02015-11-02 13:00:03 -08003558 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3559 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003560 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003561
3562 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003563 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003564 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003565 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003566 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003567 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003568 }
Robert Carr2047fae2016-11-28 14:09:09 -08003569 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003570 }
3571}
3572
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003573void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003574 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003575{
3576 String8 name;
3577 if (index < args.size()) {
3578 name = String8(args[index]);
3579 index++;
3580 }
3581
Robert Carr2047fae2016-11-28 14:09:09 -08003582 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003583 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003584 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003585 }
Robert Carr2047fae2016-11-28 14:09:09 -08003586 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003587
Svetoslavd85084b2014-03-20 10:28:31 -07003588 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003589}
3590
Jamie Gennis6547ff42013-07-16 20:12:42 -07003591// This should only be called from the main thread. Otherwise it would need
3592// the lock and should use mCurrentState rather than mDrawingState.
3593void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003594 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003595 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003596 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003597
3598 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3599}
3600
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003601void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003602{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003603 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003604 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3605
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003606 if (isLayerTripleBufferingDisabled())
3607 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003608
3609 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003610 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003611 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003612 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003613 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3614 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003615 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003616}
3617
Dan Stozab90cf072015-03-05 11:05:59 -08003618void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3619{
3620 result.appendFormat("Static screen stats:\n");
3621 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3622 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3623 float percent = 100.0f *
3624 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3625 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3626 b + 1, bucketTimeSec, percent);
3627 }
3628 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3629 float percent = 100.0f *
3630 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3631 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3632 NUM_BUCKETS - 1, bucketTimeSec, percent);
3633}
3634
Dan Stozae77c7662016-05-13 11:37:28 -07003635void SurfaceFlinger::recordBufferingStats(const char* layerName,
3636 std::vector<OccupancyTracker::Segment>&& history) {
3637 Mutex::Autolock lock(mBufferingStatsMutex);
3638 auto& stats = mBufferingStats[layerName];
3639 for (const auto& segment : history) {
3640 if (!segment.usedThirdBuffer) {
3641 stats.twoBufferTime += segment.totalTime;
3642 }
3643 if (segment.occupancyAverage < 1.0f) {
3644 stats.doubleBufferedTime += segment.totalTime;
3645 } else if (segment.occupancyAverage < 2.0f) {
3646 stats.tripleBufferedTime += segment.totalTime;
3647 }
3648 ++stats.numSegments;
3649 stats.totalTime += segment.totalTime;
3650 }
3651}
3652
Brian Andersond6927fb2016-07-23 23:37:30 -07003653void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3654 result.appendFormat("Layer frame timestamps:\n");
3655
3656 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3657 const size_t count = currentLayers.size();
3658 for (size_t i=0 ; i<count ; i++) {
3659 currentLayers[i]->dumpFrameEvents(result);
3660 }
3661}
3662
Dan Stozae77c7662016-05-13 11:37:28 -07003663void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3664 result.append("Buffering stats:\n");
3665 result.append(" [Layer name] <Active time> <Two buffer> "
3666 "<Double buffered> <Triple buffered>\n");
3667 Mutex::Autolock lock(mBufferingStatsMutex);
3668 typedef std::tuple<std::string, float, float, float> BufferTuple;
3669 std::map<float, BufferTuple, std::greater<float>> sorted;
3670 for (const auto& statsPair : mBufferingStats) {
3671 const char* name = statsPair.first.c_str();
3672 const BufferingStats& stats = statsPair.second;
3673 if (stats.numSegments == 0) {
3674 continue;
3675 }
3676 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3677 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3678 stats.totalTime;
3679 float doubleBufferRatio = static_cast<float>(
3680 stats.doubleBufferedTime) / stats.totalTime;
3681 float tripleBufferRatio = static_cast<float>(
3682 stats.tripleBufferedTime) / stats.totalTime;
3683 sorted.insert({activeTime, {name, twoBufferRatio,
3684 doubleBufferRatio, tripleBufferRatio}});
3685 }
3686 for (const auto& sortedPair : sorted) {
3687 float activeTime = sortedPair.first;
3688 const BufferTuple& values = sortedPair.second;
3689 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3690 std::get<0>(values).c_str(), activeTime,
3691 std::get<1>(values), std::get<2>(values),
3692 std::get<3>(values));
3693 }
3694 result.append("\n");
3695}
3696
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003697void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3698 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3699
3700 // TODO: print out if wide-color mode is active or not
3701
3702 for (size_t d = 0; d < mDisplays.size(); d++) {
3703 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3704 int32_t hwcId = displayDevice->getHwcDisplayId();
3705 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3706 continue;
3707 }
3708
3709 result.appendFormat("Display %d color modes:\n", hwcId);
3710 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3711 for (auto&& mode : modes) {
3712 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3713 }
3714
3715 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3716 result.appendFormat(" Current color mode: %s (%d)\n",
3717 decodeColorMode(currentMode).c_str(), currentMode);
3718 }
3719 result.append("\n");
3720}
3721
Mathias Agopian74d211a2013-04-22 16:55:35 +02003722void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3723 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003724{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003725 bool colorize = false;
3726 if (index < args.size()
3727 && (args[index] == String16("--color"))) {
3728 colorize = true;
3729 index++;
3730 }
3731
3732 Colorizer colorizer(colorize);
3733
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003734 // figure out if we're stuck somewhere
3735 const nsecs_t now = systemTime();
3736 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3737 const nsecs_t inTransaction(mDebugInTransaction);
3738 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3739 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3740
3741 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003742 * Dump library configuration.
3743 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003744
3745 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003746 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003747 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003748 appendSfConfigString(result);
3749 appendUiConfigString(result);
3750 appendGuiConfigString(result);
3751 result.append("\n");
3752
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003753 result.append("\nWide-Color information:\n");
3754 dumpWideColorInfo(result);
3755
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003756 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003757 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003758 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003759 result.append(SyncFeatures::getInstance().toString());
3760 result.append("\n");
3761
Dan Stoza9e56aa02015-11-02 13:00:03 -08003762 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3763
Andy McFadden41d67d72014-04-25 16:58:34 -07003764 colorizer.bold(result);
3765 result.append("DispSync configuration: ");
3766 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003767 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003768 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003769 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003770 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003771 result.append("\n");
3772
Dan Stozab90cf072015-03-05 11:05:59 -08003773 // Dump static screen stats
3774 result.append("\n");
3775 dumpStaticScreenStats(result);
3776 result.append("\n");
3777
Dan Stozae77c7662016-05-13 11:37:28 -07003778 dumpBufferingStats(result);
3779
Andy McFadden4803b742012-09-24 19:07:20 -07003780 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003781 * Dump the visible layer list
3782 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003783 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003784 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003785 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003786 mCurrentState.traverseInZOrder([&](Layer* layer) {
Kalle Raitaa099a242017-01-11 11:17:29 -08003787 result.append(to_string(layer->getLayerDebugInfo()).c_str());
Robert Carr2047fae2016-11-28 14:09:09 -08003788 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003789
3790 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003791 * Dump Display state
3792 */
3793
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003794 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003795 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003796 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003797 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3798 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003799 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003800 }
3801
3802 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003803 * Dump SurfaceFlinger global state
3804 */
3805
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003806 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003807 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003808 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003809
Mathias Agopian888c8222012-08-04 21:10:38 -07003810 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003811 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003812
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003813 colorizer.bold(result);
3814 result.appendFormat("EGL implementation : %s\n",
3815 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3816 colorizer.reset(result);
3817 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003818 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003819
Mathias Agopian875d8e12013-06-07 15:35:48 -07003820 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003821
Mathias Agopian42977342012-08-05 00:40:46 -07003822 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003823 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3824 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003825 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003826 " last eglSwapBuffers() time: %f us\n"
3827 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003828 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003829 " refresh-rate : %f fps\n"
3830 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003831 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003832 " gpu_to_cpu_unsupported : %d\n"
3833 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003834 mLastSwapBufferTime/1000.0,
3835 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003836 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003837 1e9 / activeConfig->getVsyncPeriod(),
3838 activeConfig->getDpiX(),
3839 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003840 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003841
Mathias Agopian74d211a2013-04-22 16:55:35 +02003842 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003843 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003844
Mathias Agopian74d211a2013-04-22 16:55:35 +02003845 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003846 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003847
3848 /*
3849 * VSYNC state
3850 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003851 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003852 result.append("\n");
3853
3854 /*
3855 * HWC layer minidump
3856 */
3857 for (size_t d = 0; d < mDisplays.size(); d++) {
3858 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3859 int32_t hwcId = displayDevice->getHwcDisplayId();
3860 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3861 continue;
3862 }
3863
3864 result.appendFormat("Display %d HWC layers:\n", hwcId);
3865 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003866 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003867 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003868 });
Dan Stozae22aec72016-08-01 13:20:59 -07003869 result.append("\n");
3870 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003871
3872 /*
3873 * Dump HWComposer state
3874 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003875 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003876 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003877 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003878 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003879 result.appendFormat(" h/w composer %s\n",
3880 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003881 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003882
3883 /*
3884 * Dump gralloc state
3885 */
3886 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3887 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003888
3889 /*
3890 * Dump VrFlinger state if in use.
3891 */
3892 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3893 result.append("VrFlinger state:\n");
3894 result.append(mVrFlinger->Dump().c_str());
3895 result.append("\n");
3896 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003897}
3898
Mathias Agopian13127d82013-03-05 17:47:11 -08003899const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003900SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003901 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003902 wp<IBinder> dpy;
3903 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3904 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3905 dpy = mDisplays.keyAt(i);
3906 break;
3907 }
3908 }
3909 if (dpy == NULL) {
3910 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3911 // Just use the primary display so we have something to return
3912 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3913 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003914 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003915}
3916
Keun young Park63f165f2012-08-31 10:53:36 -07003917bool SurfaceFlinger::startDdmConnection()
3918{
3919 void* libddmconnection_dso =
3920 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3921 if (!libddmconnection_dso) {
3922 return false;
3923 }
3924 void (*DdmConnection_start)(const char* name);
3925 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003926 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003927 if (!DdmConnection_start) {
3928 dlclose(libddmconnection_dso);
3929 return false;
3930 }
3931 (*DdmConnection_start)(getServiceName());
3932 return true;
3933}
3934
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003935status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003936 switch (code) {
3937 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003938 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003939 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003940 case CLEAR_ANIMATION_FRAME_STATS:
3941 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003942 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003943 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003944 {
3945 // codes that require permission check
3946 IPCThreadState* ipc = IPCThreadState::self();
3947 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003948 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003949 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003950 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003951 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003952 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003953 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003954 break;
3955 }
Robert Carr1db73f62016-12-21 12:58:51 -08003956 /*
3957 * Calling setTransactionState is safe, because you need to have been
3958 * granted a reference to Client* and Handle* to do anything with it.
3959 *
3960 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3961 */
3962 case SET_TRANSACTION_STATE:
3963 case CREATE_SCOPED_CONNECTION:
3964 {
3965 return OK;
3966 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003967 case CAPTURE_SCREEN:
3968 {
3969 // codes that require permission check
3970 IPCThreadState* ipc = IPCThreadState::self();
3971 const int pid = ipc->getCallingPid();
3972 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003973 if ((uid != AID_GRAPHICS) &&
3974 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003975 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003976 return PERMISSION_DENIED;
3977 }
3978 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003979 }
3980 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003981 return OK;
3982}
3983
3984status_t SurfaceFlinger::onTransact(
3985 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3986{
3987 status_t credentialCheck = CheckTransactCodeCredentials(code);
3988 if (credentialCheck != OK) {
3989 return credentialCheck;
3990 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003991
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003992 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3993 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003994 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003995 IPCThreadState* ipc = IPCThreadState::self();
3996 const int uid = ipc->getCallingUid();
3997 if (CC_UNLIKELY(uid != AID_SYSTEM
3998 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003999 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004000 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004001 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004002 return PERMISSION_DENIED;
4003 }
4004 int n;
4005 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004006 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004007 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004008 return NO_ERROR;
4009 case 1002: // SHOW_UPDATES
4010 n = data.readInt32();
4011 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004012 invalidateHwcGeometry();
4013 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004014 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004015 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004016 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004017 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004018 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004019 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004020 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004021 setTransactionFlags(
4022 eTransactionNeeded|
4023 eDisplayTransactionNeeded|
4024 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004025 return NO_ERROR;
4026 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004027 case 1006:{ // send empty update
4028 signalRefresh();
4029 return NO_ERROR;
4030 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004031 case 1008: // toggle use of hw composer
4032 n = data.readInt32();
4033 mDebugDisableHWC = n ? 1 : 0;
4034 invalidateHwcGeometry();
4035 repaintEverything();
4036 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004037 case 1009: // toggle use of transform hint
4038 n = data.readInt32();
4039 mDebugDisableTransformHint = n ? 1 : 0;
4040 invalidateHwcGeometry();
4041 repaintEverything();
4042 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004043 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004044 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004045 reply->writeInt32(0);
4046 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004047 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004048 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004049 return NO_ERROR;
4050 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004051 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004052 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004053 return NO_ERROR;
4054 }
4055 case 1014: {
4056 // daltonize
4057 n = data.readInt32();
4058 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004059 case 1:
4060 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4061 break;
4062 case 2:
4063 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4064 break;
4065 case 3:
4066 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4067 break;
4068 default:
4069 mDaltonizer.setType(ColorBlindnessType::None);
4070 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004071 }
4072 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004073 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004074 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004075 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004076 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004077 invalidateHwcGeometry();
4078 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004079 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004080 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004081 case 1015: {
4082 // apply a color matrix
4083 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004084 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004085 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004086 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004087 for (size_t j = 0; j < 4; j++) {
4088 mColorMatrix[i][j] = data.readFloat();
4089 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004090 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004091 } else {
4092 mColorMatrix = mat4();
4093 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004094
4095 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4096 // the division by w in the fragment shader
4097 float4 lastRow(transpose(mColorMatrix)[3]);
4098 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4099 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4100 }
4101
Alan Viverette9c5a3332013-09-12 20:04:35 -07004102 invalidateHwcGeometry();
4103 repaintEverything();
4104 return NO_ERROR;
4105 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004106 // This is an experimental interface
4107 // Needs to be shifted to proper binder interface when we productize
4108 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004109 n = data.readInt32();
4110 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004111 return NO_ERROR;
4112 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004113 case 1017: {
4114 n = data.readInt32();
4115 mForceFullDamage = static_cast<bool>(n);
4116 return NO_ERROR;
4117 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004118 case 1018: { // Modify Choreographer's phase offset
4119 n = data.readInt32();
4120 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4121 return NO_ERROR;
4122 }
4123 case 1019: { // Modify SurfaceFlinger's phase offset
4124 n = data.readInt32();
4125 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4126 return NO_ERROR;
4127 }
Irvel468051e2016-06-13 16:44:44 -07004128 case 1020: { // Layer updates interceptor
4129 n = data.readInt32();
4130 if (n) {
4131 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004132 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004133 }
4134 else{
4135 ALOGV("Interceptor disabled");
4136 mInterceptor.disable();
4137 }
4138 return NO_ERROR;
4139 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004140 case 1021: { // Disable HWC virtual displays
4141 n = data.readInt32();
4142 mUseHwcVirtualDisplays = !n;
4143 return NO_ERROR;
4144 }
Romain Guy0147a172017-06-01 13:53:56 -07004145 case 1022: { // Set saturation boost
4146 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4147
4148 invalidateHwcGeometry();
4149 repaintEverything();
4150 return NO_ERROR;
4151 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004152 }
4153 }
4154 return err;
4155}
4156
Steven Thomas6d8110b2017-08-31 18:24:21 -07004157void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004158 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004159 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004160}
4161
Steven Thomas6d8110b2017-08-31 18:24:21 -07004162void SurfaceFlinger::repaintEverything() {
4163 ConditionalLock _l(mStateLock,
4164 std::this_thread::get_id() != mMainThreadId);
4165 repaintEverythingLocked();
4166}
4167
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004168// Checks that the requested width and height are valid and updates them to the display dimensions
4169// if they are set to 0
4170static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4171 Transform::orientation_flags rotation,
4172 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4173 // get screen geometry
4174 uint32_t displayWidth = displayDevice->getWidth();
4175 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004176
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004177 if (rotation & Transform::ROT_90) {
4178 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004179 }
4180
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004181 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4182 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4183 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4184 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004185 }
4186
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004187 if (*requestedWidth == 0) {
4188 *requestedWidth = displayWidth;
4189 }
4190 if (*requestedHeight == 0) {
4191 *requestedHeight = displayHeight;
4192 }
4193
4194 return NO_ERROR;
4195}
4196
4197// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4198class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004199public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004200 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4201 ~WindowDisconnector() {
4202 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004203 }
4204
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004205private:
4206 ANativeWindow* mWindow;
4207 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004208};
4209
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004210static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4211 uint32_t requestedHeight, bool hasWideColorDisplay,
4212 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4213 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4214 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4215
4216 int err = 0;
4217 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4218 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4219 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4220 err |= native_window_set_usage(window, usage);
4221
4222 if (hasWideColorDisplay) {
4223 err |= native_window_set_buffers_data_space(window,
4224 renderEngineUsesWideColor
4225 ? HAL_DATASPACE_DISPLAY_P3
4226 : HAL_DATASPACE_V0_SRGB);
4227 }
4228
4229 if (err != NO_ERROR) {
4230 return BAD_VALUE;
4231 }
4232
4233 /* TODO: Once we have the sync framework everywhere this can use
4234 * server-side waits on the fence that dequeueBuffer returns.
4235 */
4236 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4237 if (err != NO_ERROR) {
4238 return err;
4239 }
4240
4241 return NO_ERROR;
4242}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004243
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004244status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4245 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004246 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004247 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004248 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004249 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004250
4251 if (CC_UNLIKELY(display == 0))
4252 return BAD_VALUE;
4253
4254 if (CC_UNLIKELY(producer == 0))
4255 return BAD_VALUE;
4256
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004257 // if we have secure windows on this display, never allow the screen capture
4258 // unless the producer interface is local (i.e.: we can take a screenshot for
4259 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004260 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004261
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004262 // Convert to surfaceflinger's internal rotation type.
4263 Transform::orientation_flags rotationFlags;
4264 switch (rotation) {
4265 case ISurfaceComposer::eRotateNone:
4266 rotationFlags = Transform::ROT_0;
4267 break;
4268 case ISurfaceComposer::eRotate90:
4269 rotationFlags = Transform::ROT_90;
4270 break;
4271 case ISurfaceComposer::eRotate180:
4272 rotationFlags = Transform::ROT_180;
4273 break;
4274 case ISurfaceComposer::eRotate270:
4275 rotationFlags = Transform::ROT_270;
4276 break;
4277 default:
4278 rotationFlags = Transform::ROT_0;
4279 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4280 break;
4281 }
4282
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004283 { // Autolock scope
4284 Mutex::Autolock lock(mStateLock);
4285 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4286 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004287 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004288
4289 // create a surface (because we're a producer, and we need to
4290 // dequeue/queue a buffer)
4291 sp<Surface> surface = new Surface(producer, false);
4292
4293 // Put the screenshot Surface into async mode so that
4294 // Layer::headFenceHasSignaled will always return true and we'll latch the
4295 // first buffer regardless of whether or not its acquire fence has
4296 // signaled. This is needed to avoid a race condition in the rotation
4297 // animation. See b/30209608
4298 surface->setAsyncMode(true);
4299
4300 ANativeWindow* window = surface.get();
4301
4302 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4303 if (result != NO_ERROR) {
4304 return result;
4305 }
4306 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4307
4308 ANativeWindowBuffer* buffer = nullptr;
4309 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4310 getRenderEngine().usesWideColor(), &buffer);
4311 if (result != NO_ERROR) {
4312 return result;
4313 }
4314
4315 // This mutex protects syncFd and captureResult for communication of the return values from the
4316 // main thread back to this Binder thread
4317 std::mutex captureMutex;
4318 std::condition_variable captureCondition;
4319 std::unique_lock<std::mutex> captureLock(captureMutex);
4320 int syncFd = -1;
4321 std::optional<status_t> captureResult;
4322
4323 sp<LambdaMessage> message = new LambdaMessage([&]() {
4324 // If there is a refresh pending, bug out early and tell the binder thread to try again
4325 // after the refresh.
4326 if (mRefreshPending) {
4327 ATRACE_NAME("Skipping screenshot for now");
4328 std::unique_lock<std::mutex> captureLock(captureMutex);
4329 captureResult = std::make_optional<status_t>(EAGAIN);
4330 captureCondition.notify_one();
4331 return;
4332 }
4333
4334 status_t result = NO_ERROR;
4335 int fd = -1;
4336 {
4337 Mutex::Autolock _l(mStateLock);
4338 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4339 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4340 minLayerZ, maxLayerZ, useIdentityTransform,
4341 rotationFlags, isLocalScreenshot, &fd);
4342 }
4343
4344 {
4345 std::unique_lock<std::mutex> captureLock(captureMutex);
4346 syncFd = fd;
4347 captureResult = std::make_optional<status_t>(result);
4348 captureCondition.notify_one();
4349 }
4350 });
4351
4352 result = postMessageAsync(message);
4353 if (result == NO_ERROR) {
4354 captureCondition.wait(captureLock, [&]() { return captureResult; });
4355 while (*captureResult == EAGAIN) {
4356 captureResult.reset();
4357 result = postMessageAsync(message);
4358 if (result != NO_ERROR) {
4359 return result;
4360 }
4361 captureCondition.wait(captureLock, [&]() { return captureResult; });
4362 }
4363 result = *captureResult;
4364 }
4365
4366 if (result == NO_ERROR) {
4367 // queueBuffer takes ownership of syncFd
4368 result = window->queueBuffer(window, buffer, syncFd);
4369 }
4370
4371 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004372}
4373
Mathias Agopian180f10d2013-04-10 22:55:41 -07004374
4375void SurfaceFlinger::renderScreenImplLocked(
4376 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004377 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004378 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004379 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004380{
4381 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004382 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004383
4384 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004385 const int32_t hw_w = hw->getWidth();
4386 const int32_t hw_h = hw->getHeight();
4387 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004388 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004389
Dan Stozac1879002014-05-22 15:59:05 -07004390 // if a default or invalid sourceCrop is passed in, set reasonable values
4391 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4392 !sourceCrop.isValid()) {
4393 sourceCrop.setLeftTop(Point(0, 0));
4394 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4395 }
4396
4397 // ensure that sourceCrop is inside screen
4398 if (sourceCrop.left < 0) {
4399 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4400 }
Dan Stozabe31f442014-06-11 11:20:54 -07004401 if (sourceCrop.right > hw_w) {
4402 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004403 }
4404 if (sourceCrop.top < 0) {
4405 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4406 }
Dan Stozabe31f442014-06-11 11:20:54 -07004407 if (sourceCrop.bottom > hw_h) {
4408 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004409 }
4410
Romain Guy88d37dd2017-05-26 17:57:05 -07004411#ifdef USE_HWC2
4412 engine.setWideColor(hw->getWideColorSupport());
4413 engine.setColorMode(hw->getActiveColorMode());
4414#endif
4415
Mathias Agopian180f10d2013-04-10 22:55:41 -07004416 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004417 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004418
4419 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004420 engine.setViewportAndProjection(
4421 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004422 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004423
4424 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004425 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004426
Robert Carr1f0a16a2016-10-24 16:27:39 -07004427 // We loop through the first level of layers without traversing,
4428 // as we need to interpret min/max layer Z in the top level Z space.
4429 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004430 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004431 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004432 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004433 const Layer::State& state(layer->getDrawingState());
4434 if (state.z < minLayerZ || state.z > maxLayerZ) {
4435 continue;
4436 }
Dan Stoza412903f2017-04-27 13:42:17 -07004437 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004438 if (!layer->isVisible()) {
4439 return;
4440 }
4441 if (filtering) layer->setFiltering(true);
4442 layer->draw(hw, useIdentityTransform);
4443 if (filtering) layer->setFiltering(false);
4444 });
4445 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004446
Mathias Agopian931bda12013-08-28 18:11:46 -07004447 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004448}
4449
Dan Stozaabcda352017-06-01 14:37:39 -07004450// A simple RAII class that holds an EGLImage and destroys it either:
4451// a) When the destroy() method is called
4452// b) When the object goes out of scope
4453class ImageHolder {
4454public:
4455 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4456 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004457
Dan Stozaabcda352017-06-01 14:37:39 -07004458 void destroy() {
4459 if (mImage != EGL_NO_IMAGE_KHR) {
4460 eglDestroyImageKHR(mDisplay, mImage);
4461 mImage = EGL_NO_IMAGE_KHR;
4462 }
4463 }
4464
4465private:
4466 const EGLDisplay mDisplay;
4467 EGLImageKHR mImage;
4468};
4469
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004470status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4471 ANativeWindowBuffer* buffer, Rect sourceCrop,
4472 uint32_t reqWidth, uint32_t reqHeight,
4473 int32_t minLayerZ, int32_t maxLayerZ,
4474 bool useIdentityTransform,
4475 Transform::orientation_flags rotation,
4476 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004477 ATRACE_CALL();
4478
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004479 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004480 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004481 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004482 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004483 (state.z < minLayerZ || state.z > maxLayerZ)) {
4484 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004485 }
Dan Stoza412903f2017-04-27 13:42:17 -07004486 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004487 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4488 layer->isSecure());
4489 });
4490 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004491
4492 if (!isLocalScreenshot && secureLayerIsVisible) {
4493 ALOGW("FB is protected: PERMISSION_DENIED");
4494 return PERMISSION_DENIED;
4495 }
4496
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004497 int syncFd = -1;
4498 // create an EGLImage from the buffer so we can later
4499 // turn it into a texture
4500 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4501 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4502 if (image == EGL_NO_IMAGE_KHR) {
4503 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004504 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004505
Dan Stozaabcda352017-06-01 14:37:39 -07004506 // This will automatically destroy the image if we return before calling its destroy method
4507 ImageHolder imageHolder(mEGLDisplay, image);
4508
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004509 // this binds the given EGLImage as a framebuffer for the
4510 // duration of this scope.
4511 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004512 if (imageBond.getStatus() != NO_ERROR) {
4513 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004514 return INVALID_OPERATION;
4515 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004516
Dan Stozaabcda352017-06-01 14:37:39 -07004517 // this will in fact render into our dequeued buffer
4518 // via an FBO, which means we didn't have to create
4519 // an EGLSurface and therefore we're not
4520 // dependent on the context's EGLConfig.
4521 renderScreenImplLocked(
4522 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4523 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004524
Dan Stozaabcda352017-06-01 14:37:39 -07004525 // Attempt to create a sync khr object that can produce a sync point. If that
4526 // isn't available, create a non-dupable sync object in the fallback path and
4527 // wait on it directly.
4528 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4529 if (!DEBUG_SCREENSHOTS) {
4530 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4531 // native fence fd will not be populated until flush() is done.
4532 getRenderEngine().flush();
4533 }
4534
4535 if (sync != EGL_NO_SYNC_KHR) {
4536 // get the sync fd
4537 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4538 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4539 ALOGW("captureScreen: failed to dup sync khr object");
4540 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004541 }
Dan Stozaabcda352017-06-01 14:37:39 -07004542 eglDestroySyncKHR(mEGLDisplay, sync);
4543 } else {
4544 // fallback path
4545 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004546 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004547 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4548 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4549 EGLint eglErr = eglGetError();
4550 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4551 ALOGW("captureScreen: fence wait timed out");
4552 } else {
4553 ALOGW_IF(eglErr != EGL_SUCCESS,
4554 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004555 }
4556 eglDestroySyncKHR(mEGLDisplay, sync);
4557 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004558 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004559 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004560 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004561 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004562
4563 if (DEBUG_SCREENSHOTS) {
4564 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4565 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4566 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4567 hw, minLayerZ, maxLayerZ);
4568 delete [] pixels;
4569 }
4570
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004571 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004572 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004573
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004574 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004575}
4576
Mathias Agopiand5556842013-09-19 17:08:37 -07004577void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004578 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004579 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004580 for (size_t y=0 ; y<h ; y++) {
4581 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4582 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004583 if (p[x] != 0xFF000000) return;
4584 }
4585 }
4586 ALOGE("*** we just took a black screenshot ***\n"
4587 "requested minz=%d, maxz=%d, layerStack=%d",
4588 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004589
Robert Carr2047fae2016-11-28 14:09:09 -08004590 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004591 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004592 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004593 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004594 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004595 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004596 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4597 layer->isVisible() ? '+' : '-',
4598 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004599 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004600 i++;
4601 });
4602 }
4603 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004604 }
4605}
4606
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004607// ---------------------------------------------------------------------------
4608
Dan Stoza412903f2017-04-27 13:42:17 -07004609void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4610 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004611}
4612
Dan Stoza412903f2017-04-27 13:42:17 -07004613void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4614 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004615}
4616
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004617}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004618
4619
4620#if defined(__gl_h_)
4621#error "don't include gl/gl.h in this file"
4622#endif
4623
4624#if defined(__gl2_h_)
4625#error "don't include gl2/gl2.h in this file"
4626#endif