blob: 2a9f923d3e315ce2d575f53bc6e7b4a8f4441f08 [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;
635 signalTransaction();
636 };
637 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
638 vrFlingerRequestDisplayCallback);
639 if (!mVrFlinger) {
640 ALOGE("Failed to start vrflinger");
641 }
642 }
643
Jamie Gennisd1700752013-10-14 12:22:52 -0700644 mEventControlThread = new EventControlThread(this);
645 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
646
Mathias Agopian92a979a2012-08-02 18:32:23 -0700647 // initialize our drawing state
648 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700649
Andy McFadden13a082e2012-08-24 10:16:42 -0700650 // set initial conditions (e.g. unblank default device)
651 initializeDisplays();
652
Dan Stoza4e637772016-07-28 13:31:51 -0700653 mRenderEngine->primeCache();
654
Wei Wangf9b05ee2017-07-19 20:59:39 -0700655 // Inform native graphics APIs whether the present timestamp is supported:
656 if (getHwComposer().hasCapability(
657 HWC2::Capability::PresentFenceIsNotReliable)) {
658 mStartPropertySetThread = new StartPropertySetThread(false);
659 } else {
660 mStartPropertySetThread = new StartPropertySetThread(true);
661 }
662
663 if (mStartPropertySetThread->Start() != NO_ERROR) {
664 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800665 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800666
Dan Stoza9e56aa02015-11-02 13:00:03 -0800667 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700668}
669
Romain Guy11d63f42017-07-20 12:47:14 -0700670void SurfaceFlinger::readPersistentProperties() {
671 char value[PROPERTY_VALUE_MAX];
672
673 property_get("persist.sys.sf.color_saturation", value, "1.0");
674 mSaturation = atof(value);
675 ALOGV("Saturation is set to %.2f", mSaturation);
676}
677
Mathias Agopiana67e4182012-06-19 17:26:12 -0700678void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800679 // Start boot animation service by setting a property mailbox
680 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700681 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800682 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700683 if (mStartPropertySetThread->join() != NO_ERROR) {
684 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800685 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700686}
687
Mathias Agopian875d8e12013-06-07 15:35:48 -0700688size_t SurfaceFlinger::getMaxTextureSize() const {
689 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700690}
691
Mathias Agopian875d8e12013-06-07 15:35:48 -0700692size_t SurfaceFlinger::getMaxViewportDims() const {
693 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700694}
695
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800696// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800697
Jamie Gennis582270d2011-08-17 18:19:00 -0700698bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800699 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800700 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800701 return authenticateSurfaceTextureLocked(bufferProducer);
702}
703
704bool SurfaceFlinger::authenticateSurfaceTextureLocked(
705 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800706 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700707 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800708}
709
Brian Anderson6b376712017-04-04 10:51:39 -0700710status_t SurfaceFlinger::getSupportedFrameTimestamps(
711 std::vector<FrameEvent>* outSupported) const {
712 *outSupported = {
713 FrameEvent::REQUESTED_PRESENT,
714 FrameEvent::ACQUIRE,
715 FrameEvent::LATCH,
716 FrameEvent::FIRST_REFRESH_START,
717 FrameEvent::LAST_REFRESH_START,
718 FrameEvent::GPU_COMPOSITION_DONE,
719 FrameEvent::DEQUEUE_READY,
720 FrameEvent::RELEASE,
721 };
722 if (!getHwComposer().hasCapability(
723 HWC2::Capability::PresentFenceIsNotReliable)) {
724 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
725 }
726 return NO_ERROR;
727}
728
Dan Stoza7f7da322014-05-02 15:26:25 -0700729status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
730 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700731 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700732 return BAD_VALUE;
733 }
734
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500735 if (!display.get())
736 return NAME_NOT_FOUND;
737
Jesse Hall692c7232012-11-08 15:41:56 -0800738 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700739 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800740 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700741 type = i;
742 break;
743 }
744 }
745
746 if (type < 0) {
747 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700748 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700749
Mathias Agopian8b736f12012-08-13 17:54:26 -0700750 // TODO: Not sure if display density should handled by SF any longer
751 class Density {
752 static int getDensityFromProperty(char const* propName) {
753 char property[PROPERTY_VALUE_MAX];
754 int density = 0;
755 if (property_get(propName, property, NULL) > 0) {
756 density = atoi(property);
757 }
758 return density;
759 }
760 public:
761 static int getEmuDensity() {
762 return getDensityFromProperty("qemu.sf.lcd_density"); }
763 static int getBuildDensity() {
764 return getDensityFromProperty("ro.sf.lcd_density"); }
765 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700766
Dan Stoza7f7da322014-05-02 15:26:25 -0700767 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700768
Dan Stoza9e56aa02015-11-02 13:00:03 -0800769 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700770 DisplayInfo info = DisplayInfo();
771
Dan Stoza9e56aa02015-11-02 13:00:03 -0800772 float xdpi = hwConfig->getDpiX();
773 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700774
775 if (type == DisplayDevice::DISPLAY_PRIMARY) {
776 // The density of the device is provided by a build property
777 float density = Density::getBuildDensity() / 160.0f;
778 if (density == 0) {
779 // the build doesn't provide a density -- this is wrong!
780 // use xdpi instead
781 ALOGE("ro.sf.lcd_density must be defined as a build property");
782 density = xdpi / 160.0f;
783 }
784 if (Density::getEmuDensity()) {
785 // if "qemu.sf.lcd_density" is specified, it overrides everything
786 xdpi = ydpi = density = Density::getEmuDensity();
787 density /= 160.0f;
788 }
789 info.density = density;
790
791 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000792 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
793 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700794 } else {
795 // TODO: where should this value come from?
796 static const int TV_DENSITY = 213;
797 info.density = TV_DENSITY / 160.0f;
798 info.orientation = 0;
799 }
800
Dan Stoza9e56aa02015-11-02 13:00:03 -0800801 info.w = hwConfig->getWidth();
802 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700803 info.xdpi = xdpi;
804 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800805 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900806 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800807
Andy McFadden91b2ca82014-06-13 14:04:23 -0700808 // This is how far in advance a buffer must be queued for
809 // presentation at a given time. If you want a buffer to appear
810 // on the screen at time N, you must submit the buffer before
811 // (N - presentationDeadline).
812 //
813 // Normally it's one full refresh period (to give SF a chance to
814 // latch the buffer), but this can be reduced by configuring a
815 // DispSync offset. Any additional delays introduced by the hardware
816 // composer or panel must be accounted for here.
817 //
818 // We add an additional 1ms to allow for processing time and
819 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800821 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700822
823 // All non-virtual displays are currently considered secure.
824 info.secure = true;
825
Michael Wright28f24d02016-07-12 13:30:53 -0700826 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 }
828
Dan Stoza7f7da322014-05-02 15:26:25 -0700829 return NO_ERROR;
830}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700831
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800832status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700833 DisplayStatInfo* stats) {
834 if (stats == NULL) {
835 return BAD_VALUE;
836 }
837
838 // FIXME for now we always return stats for the primary display
839 memset(stats, 0, sizeof(*stats));
840 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
841 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
842 return NO_ERROR;
843}
844
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700845int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800846 if (display == NULL) {
847 ALOGE("%s : display is NULL", __func__);
848 return BAD_VALUE;
849 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700850
851 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700852 if (device != NULL) {
853 return device->getActiveConfig();
854 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700855
Dan Stoza24a42e92015-03-09 10:04:11 -0700856 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700857}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700858
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700859void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
860 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
861 this);
862 int32_t type = hw->getDisplayType();
863 int currentMode = hw->getActiveConfig();
864
865 if (mode == currentMode) {
866 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
867 return;
868 }
869
870 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
871 ALOGW("Trying to set config for virtual display");
872 return;
873 }
874
875 hw->setActiveConfig(mode);
876 getHwComposer().setActiveConfig(type, mode);
877}
878
879status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
880 class MessageSetActiveConfig: public MessageBase {
881 SurfaceFlinger& mFlinger;
882 sp<IBinder> mDisplay;
883 int mMode;
884 public:
885 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
886 int mode) :
887 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
888 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700889 Vector<DisplayInfo> configs;
890 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700891 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700892 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700893 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700894 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700895 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700896 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
897 if (hw == NULL) {
898 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700899 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700900 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
901 ALOGW("Attempt to set active config = %d for virtual display",
902 mMode);
903 } else {
904 mFlinger.setActiveConfigInternal(hw, mMode);
905 }
906 return true;
907 }
908 };
909 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
910 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700911 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700912}
Michael Wright28f24d02016-07-12 13:30:53 -0700913status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
914 Vector<android_color_mode_t>* outColorModes) {
915 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
916 return BAD_VALUE;
917 }
918
919 if (!display.get()) {
920 return NAME_NOT_FOUND;
921 }
922
923 int32_t type = NAME_NOT_FOUND;
924 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
925 if (display == mBuiltinDisplays[i]) {
926 type = i;
927 break;
928 }
929 }
930
931 if (type < 0) {
932 return type;
933 }
934
935 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
936 outColorModes->clear();
937 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
938
939 return NO_ERROR;
940}
941
942android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700943 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700944 if (device != nullptr) {
945 return device->getActiveColorMode();
946 }
947 return static_cast<android_color_mode_t>(BAD_VALUE);
948}
949
950void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
951 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700952 int32_t type = hw->getDisplayType();
953 android_color_mode_t currentMode = hw->getActiveColorMode();
954
955 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700956 return;
957 }
958
959 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
960 ALOGW("Trying to set config for virtual display");
961 return;
962 }
963
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600964 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
965 hw->getDisplayType());
966
Michael Wright28f24d02016-07-12 13:30:53 -0700967 hw->setActiveColorMode(mode);
968 getHwComposer().setActiveColorMode(type, mode);
969}
970
971
972status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
973 android_color_mode_t colorMode) {
974 class MessageSetActiveColorMode: public MessageBase {
975 SurfaceFlinger& mFlinger;
976 sp<IBinder> mDisplay;
977 android_color_mode_t mMode;
978 public:
979 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
980 android_color_mode_t mode) :
981 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
982 virtual bool handler() {
983 Vector<android_color_mode_t> modes;
984 mFlinger.getDisplayColorModes(mDisplay, &modes);
985 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
986 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600987 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
988 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700989 return true;
990 }
991 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
992 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600993 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
994 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700995 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600996 ALOGW("Attempt to set active color mode %s %d for virtual display",
997 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700998 } else {
999 mFlinger.setActiveColorModeInternal(hw, mMode);
1000 }
1001 return true;
1002 }
1003 };
1004 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1005 postMessageSync(msg);
1006 return NO_ERROR;
1007}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001008
Svetoslavd85084b2014-03-20 10:28:31 -07001009status_t SurfaceFlinger::clearAnimationFrameStats() {
1010 Mutex::Autolock _l(mStateLock);
1011 mAnimFrameTracker.clearStats();
1012 return NO_ERROR;
1013}
1014
1015status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1016 Mutex::Autolock _l(mStateLock);
1017 mAnimFrameTracker.getStats(outStats);
1018 return NO_ERROR;
1019}
1020
Dan Stozac4f471e2016-03-24 09:31:08 -07001021status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1022 HdrCapabilities* outCapabilities) const {
1023 Mutex::Autolock _l(mStateLock);
1024
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001025 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001026 if (displayDevice == nullptr) {
1027 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1028 return BAD_VALUE;
1029 }
1030
1031 std::unique_ptr<HdrCapabilities> capabilities =
1032 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1033 if (capabilities) {
1034 std::swap(*outCapabilities, *capabilities);
1035 } else {
1036 return BAD_VALUE;
1037 }
1038
1039 return NO_ERROR;
1040}
1041
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001042status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1043 if (enable == mInjectVSyncs) {
1044 return NO_ERROR;
1045 }
1046
1047 if (enable) {
1048 mInjectVSyncs = enable;
1049 ALOGV("VSync Injections enabled");
1050 if (mVSyncInjector.get() == nullptr) {
1051 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001052 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001053 }
1054 mEventQueue.setEventThread(mInjectorEventThread);
1055 } else {
1056 mInjectVSyncs = enable;
1057 ALOGV("VSync Injections disabled");
1058 mEventQueue.setEventThread(mSFEventThread);
1059 mVSyncInjector.clear();
1060 }
1061 return NO_ERROR;
1062}
1063
1064status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1065 if (!mInjectVSyncs) {
1066 ALOGE("VSync Injections not enabled");
1067 return BAD_VALUE;
1068 }
1069 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1070 ALOGV("Injecting VSync inside SurfaceFlinger");
1071 mVSyncInjector->onInjectSyncEvent(when);
1072 }
1073 return NO_ERROR;
1074}
1075
Kalle Raitaa099a242017-01-11 11:17:29 -08001076status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1077 IPCThreadState* ipc = IPCThreadState::self();
1078 const int pid = ipc->getCallingPid();
1079 const int uid = ipc->getCallingUid();
1080 if ((uid != AID_SHELL) &&
1081 !PermissionCache::checkPermission(sDump, pid, uid)) {
1082 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1083 return PERMISSION_DENIED;
1084 }
1085
1086 // Try to acquire a lock for 1s, fail gracefully
1087 const status_t err = mStateLock.timedLock(s2ns(1));
1088 const bool locked = (err == NO_ERROR);
1089 if (!locked) {
1090 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1091 return TIMED_OUT;
1092 }
1093
1094 outLayers->clear();
1095 mCurrentState.traverseInZOrder([&](Layer* layer) {
1096 outLayers->push_back(layer->getLayerDebugInfo());
1097 });
1098
1099 mStateLock.unlock();
1100 return NO_ERROR;
1101}
1102
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001103// ----------------------------------------------------------------------------
1104
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001105sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1106 ISurfaceComposer::VsyncSource vsyncSource) {
1107 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1108 return mSFEventThread->createEventConnection();
1109 } else {
1110 return mEventThread->createEventConnection();
1111 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001112}
1113
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001114// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001115
1116void SurfaceFlinger::waitForEvent() {
1117 mEventQueue.waitMessage();
1118}
1119
1120void SurfaceFlinger::signalTransaction() {
1121 mEventQueue.invalidate();
1122}
1123
1124void SurfaceFlinger::signalLayerUpdate() {
1125 mEventQueue.invalidate();
1126}
1127
1128void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001129 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001130 mEventQueue.refresh();
1131}
1132
1133status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001134 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001135 return mEventQueue.postMessage(msg, reltime);
1136}
1137
1138status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001139 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001140 status_t res = mEventQueue.postMessage(msg, reltime);
1141 if (res == NO_ERROR) {
1142 msg->wait();
1143 }
1144 return res;
1145}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001146
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001147void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001148 do {
1149 waitForEvent();
1150 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001151}
1152
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001153void SurfaceFlinger::enableHardwareVsync() {
1154 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001155 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001156 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001157 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1158 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001159 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001160 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001161}
1162
Jesse Hall948fe0c2013-10-14 12:56:09 -07001163void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001164 Mutex::Autolock _l(mHWVsyncLock);
1165
Jesse Hall948fe0c2013-10-14 12:56:09 -07001166 if (makeAvailable) {
1167 mHWVsyncAvailable = true;
1168 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001169 // Hardware vsync is not currently available, so abort the resync
1170 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001171 return;
1172 }
1173
Dan Stoza9e56aa02015-11-02 13:00:03 -08001174 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1175 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001176
1177 mPrimaryDispSync.reset();
1178 mPrimaryDispSync.setPeriod(period);
1179
1180 if (!mPrimaryHWVsyncEnabled) {
1181 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001182 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1183 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184 mPrimaryHWVsyncEnabled = true;
1185 }
1186}
1187
Jesse Hall948fe0c2013-10-14 12:56:09 -07001188void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189 Mutex::Autolock _l(mHWVsyncLock);
1190 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001191 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1192 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001193 mPrimaryDispSync.endResync();
1194 mPrimaryHWVsyncEnabled = false;
1195 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001196 if (makeUnavailable) {
1197 mHWVsyncAvailable = false;
1198 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001199}
1200
Tim Murray4a4e4a22016-04-19 16:29:23 +00001201void SurfaceFlinger::resyncWithRateLimit() {
1202 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001203
1204 // No explicit locking is needed here since EventThread holds a lock while calling this method
1205 static nsecs_t sLastResyncAttempted = 0;
1206 const nsecs_t now = systemTime();
1207 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001208 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001209 }
Dan Stoza57164302017-05-08 14:03:54 -07001210 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001211}
1212
Steven Thomasb02664d2017-07-26 18:48:28 -07001213void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1214 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001215 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001216 // Ignore any vsyncs from a previous hardware composer.
1217 if (sequenceId != mComposerSequenceId) {
1218 return;
1219 }
1220
1221 int32_t type;
1222 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001223 return;
1224 }
1225
Jamie Gennisd1700752013-10-14 12:22:52 -07001226 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001227
Jamie Gennisd1700752013-10-14 12:22:52 -07001228 { // Scope for the lock
1229 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001230 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001231 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001232 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001233 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001234
1235 if (needsHwVsync) {
1236 enableHardwareVsync();
1237 } else {
1238 disableHardwareVsync(false);
1239 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001240}
1241
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001242void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001243 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001244 *compositorTiming = mCompositorTiming;
1245}
1246
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001247void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001248 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001249 wp<IBinder> token = mBuiltinDisplays[type];
1250
1251 // All non-virtual displays are currently considered secure.
1252 const bool isSecure = true;
1253
1254 sp<IGraphicBufferProducer> producer;
1255 sp<IGraphicBufferConsumer> consumer;
1256 BufferQueue::createBufferQueue(&producer, &consumer);
1257
1258 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1259
1260 bool hasWideColorModes = false;
1261 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1262 for (android_color_mode_t colorMode : modes) {
1263 switch (colorMode) {
1264 case HAL_COLOR_MODE_DISPLAY_P3:
1265 case HAL_COLOR_MODE_ADOBE_RGB:
1266 case HAL_COLOR_MODE_DCI_P3:
1267 hasWideColorModes = true;
1268 break;
1269 default:
1270 break;
1271 }
1272 }
1273 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1274 token, fbs, producer, mRenderEngine->getEGLConfig(),
1275 hasWideColorModes && hasWideColorDisplay);
1276 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001277 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1278 if (hasWideColorModes && hasWideColorDisplay) {
1279 defaultColorMode = HAL_COLOR_MODE_SRGB;
1280 }
1281 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001282 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001283
1284 // Add the primary display token to mDrawingState so we don't try to
1285 // recreate the DisplayDevice for the primary display.
1286 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1287
1288 // make the GLContext current so that we can create textures when creating
1289 // Layers (which may happens before we render something)
1290 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001291}
1292
Steven Thomasb02664d2017-07-26 18:48:28 -07001293void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1294 hwc2_display_t display, HWC2::Connection connection,
1295 bool primaryDisplay) {
1296 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1297 sequenceId, display,
1298 connection == HWC2::Connection::Connected ?
1299 "connected" : "disconnected",
1300 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001301
Steven Thomasb02664d2017-07-26 18:48:28 -07001302 // Only lock if we're not on the main thread. This function is normally
1303 // called on a hwbinder thread, but for the primary display it's called on
1304 // the main thread with the state lock already held, so don't attempt to
1305 // acquire it here.
1306 ConditionalLock lock(mStateLock,
1307 std::this_thread::get_id() != mMainThreadId);
1308
1309 if (primaryDisplay) {
1310 mHwc->onHotplug(display, connection);
1311 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1312 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001313 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001314 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001315 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001316 if (sequenceId != mComposerSequenceId) {
1317 return;
1318 }
1319 if (mHwc->isUsingVrComposer()) {
1320 ALOGE("External displays are not supported by the vr hardware composer.");
1321 return;
1322 }
1323 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001324 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001325 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001326 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001327 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001328 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1329 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001330 }
1331 setTransactionFlags(eDisplayTransactionNeeded);
1332
Andy McFadden9e9689c2012-10-10 18:17:51 -07001333 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001334 }
Mathias Agopian86303202012-07-24 22:46:10 -07001335}
1336
Steven Thomasb02664d2017-07-26 18:48:28 -07001337void SurfaceFlinger::onRefreshReceived(int sequenceId,
1338 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001339 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001340 if (sequenceId != mComposerSequenceId) {
1341 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001342 }
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001344}
1345
Dan Stoza9e56aa02015-11-02 13:00:03 -08001346void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001347 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001348 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001349 getHwComposer().setVsyncEnabled(disp,
1350 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001351}
1352
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001353// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001354void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001355 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001356 // Clear the drawing state so that the logic inside of
1357 // handleTransactionLocked will fire. It will determine the delta between
1358 // mCurrentState and mDrawingState and re-apply all changes when we make the
1359 // transition.
1360 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001362 mDisplays.clear();
1363}
1364
Steven Thomas050b2c82017-03-06 11:45:16 -08001365void SurfaceFlinger::updateVrFlinger() {
1366 if (!mVrFlinger)
1367 return;
1368 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1369 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001370 return;
1371 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001372
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1374 ALOGE("Vr flinger is only supported for remote hardware composer"
1375 " service connections. Ignoring request to transition to vr"
1376 " flinger.");
1377 mVrFlingerRequestsDisplay = false;
1378 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001379 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001380
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001381 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 int currentDisplayPowerMode = getDisplayDeviceLocked(
1384 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001385
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001387 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 resetDisplayState();
1391 mHwc.reset(); // Delete the current instance before creating the new one
1392 mHwc.reset(new HWComposer(
1393 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1394 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001395
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1397 "Switched to non-remote hardware composer");
1398
1399 if (vrFlingerRequestsDisplay) {
1400 mVrFlinger->GrantDisplayOwnership();
1401 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001404
1405 mVisibleRegionsDirty = true;
1406 invalidateHwcGeometry();
1407
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001408 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001409 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1410 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1411 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001412
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 // Reset the timing values to account for the period of the swapped in HWC
1414 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1415 const nsecs_t period = activeConfig->getVsyncPeriod();
1416 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001417
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 // Use phase of 0 since phase is not known.
1419 // Use latency of 0, which will snap to the ideal latency.
1420 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001421
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001422 android_atomic_or(1, &mRepaintEverything);
1423 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001424}
1425
Mathias Agopian4fec8732012-06-29 14:12:52 -07001426void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001427 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001428 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001429 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001430 bool frameMissed = !mHadClientComposition &&
1431 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001432 (mPreviousPresentFence->getSignalTime() ==
1433 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001434 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001435 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001436 signalLayerUpdate();
1437 break;
1438 }
1439
Steven Thomas050b2c82017-03-06 11:45:16 -08001440 // Now that we're going to make it to the handleMessageTransaction()
1441 // call below it's safe to call updateVrFlinger(), which will
1442 // potentially trigger a display handoff.
1443 updateVrFlinger();
1444
Dan Stoza6b9454d2014-11-07 16:00:59 -08001445 bool refreshNeeded = handleMessageTransaction();
1446 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001447 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001448 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001449 // Signal a refresh if a transaction modified the window state,
1450 // a new buffer was latched, or if HWC has requested a full
1451 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001452 signalRefresh();
1453 }
1454 break;
1455 }
1456 case MessageQueue::REFRESH: {
1457 handleMessageRefresh();
1458 break;
1459 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001460 }
1461}
1462
Dan Stoza6b9454d2014-11-07 16:00:59 -08001463bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001464 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001465 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001466 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001467 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001468 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001469 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001470}
1471
Dan Stoza6b9454d2014-11-07 16:00:59 -08001472bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001473 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001474 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001475}
1476
1477void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001478 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001479
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001480 mRefreshPending = false;
1481
Pablo Ceballos40845df2016-01-25 17:41:15 -08001482 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001483
Brian Andersond6927fb2016-07-23 23:37:30 -07001484 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001485 rebuildLayerStacks();
1486 setUpHWComposer();
1487 doDebugFlashRegions();
1488 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001489 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001490
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001491 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001492
1493 mHadClientComposition = false;
1494 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1495 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1496 mHadClientComposition = mHadClientComposition ||
1497 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1498 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001499
Dan Stoza9e56aa02015-11-02 13:00:03 -08001500 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001501}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001502
Mathias Agopiancd60f992012-08-16 16:28:27 -07001503void SurfaceFlinger::doDebugFlashRegions()
1504{
1505 // is debugging enabled
1506 if (CC_LIKELY(!mDebugRegion))
1507 return;
1508
1509 const bool repaintEverything = mRepaintEverything;
1510 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1511 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001512 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513 // transform the dirty region into this screen's coordinate space
1514 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1515 if (!dirtyRegion.isEmpty()) {
1516 // redraw the whole screen
1517 doComposeSurfaces(hw, Region(hw->bounds()));
1518
1519 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001520 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001521 RenderEngine& engine(getRenderEngine());
1522 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1523
Mathias Agopianda27af92012-09-13 18:17:13 -07001524 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001525 }
1526 }
1527 }
1528
1529 postFramebuffer();
1530
1531 if (mDebugRegion > 1) {
1532 usleep(mDebugRegion * 1000);
1533 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001534
Dan Stoza9e56aa02015-11-02 13:00:03 -08001535 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001536 auto& displayDevice = mDisplays[displayId];
1537 if (!displayDevice->isDisplayOn()) {
1538 continue;
1539 }
1540
1541 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001542 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1543 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001544 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545}
1546
Brian Andersond6927fb2016-07-23 23:37:30 -07001547void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001548{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001549 ATRACE_CALL();
1550 ALOGV("preComposition");
1551
Mathias Agopiancd60f992012-08-16 16:28:27 -07001552 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001553 mDrawingState.traverseInZOrder([&](Layer* layer) {
1554 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555 needExtraInvalidate = true;
1556 }
Robert Carr2047fae2016-11-28 14:09:09 -08001557 });
1558
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559 if (needExtraInvalidate) {
1560 signalLayerUpdate();
1561 }
1562}
1563
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001564void SurfaceFlinger::updateCompositorTiming(
1565 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1566 std::shared_ptr<FenceTime>& presentFenceTime) {
1567 // Update queue of past composite+present times and determine the
1568 // most recently known composite to present latency.
1569 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1570 nsecs_t compositeToPresentLatency = -1;
1571 while (!mCompositePresentTimes.empty()) {
1572 CompositePresentTime& cpt = mCompositePresentTimes.front();
1573 // Cached values should have been updated before calling this method,
1574 // which helps avoid duplicate syscalls.
1575 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1576 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1577 break;
1578 }
1579 compositeToPresentLatency = displayTime - cpt.composite;
1580 mCompositePresentTimes.pop();
1581 }
1582
1583 // Don't let mCompositePresentTimes grow unbounded, just in case.
1584 while (mCompositePresentTimes.size() > 16) {
1585 mCompositePresentTimes.pop();
1586 }
1587
Brian Andersond0010582017-03-07 13:20:31 -08001588 setCompositorTimingSnapped(
1589 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1590}
1591
1592void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1593 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001594 // Integer division and modulo round toward 0 not -inf, so we need to
1595 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001596 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001597 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1598 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1599
Brian Andersond0010582017-03-07 13:20:31 -08001600 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1601 if (idealLatency <= 0) {
1602 idealLatency = vsyncInterval;
1603 }
1604
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001605 // Snap the latency to a value that removes scheduling jitter from the
1606 // composition and present times, which often have >1ms of jitter.
1607 // Reducing jitter is important if an app attempts to extrapolate
1608 // something (such as user input) to an accurate diasplay time.
1609 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1610 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001611 nsecs_t bias = vsyncInterval / 2;
1612 int64_t extraVsyncs =
1613 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1614 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1615 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001616
Brian Andersond0010582017-03-07 13:20:31 -08001617 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001618 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1619 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001620 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001621}
1622
1623void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001624{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001625 ATRACE_CALL();
1626 ALOGV("postComposition");
1627
Brian Anderson3546a3f2016-07-14 11:51:14 -07001628 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001629 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001630 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001631 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001632 }
1633
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001634 // |mStateLock| not needed as we are on the main thread
1635 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001636
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001637 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001638 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1639 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1640 glCompositionDoneFenceTime =
1641 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1642 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1643 } else {
1644 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1645 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001646
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001647 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001648 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1649 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1650 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001651
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001652 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1653 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1654
1655 // We use the refreshStartTime which might be sampled a little later than
1656 // when we started doing work for this frame, but that should be okay
1657 // since updateCompositorTiming has snapping logic.
1658 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001659 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001660 CompositorTiming compositorTiming;
1661 {
1662 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1663 compositorTiming = mCompositorTiming;
1664 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001665
Robert Carr2047fae2016-11-28 14:09:09 -08001666 mDrawingState.traverseInZOrder([&](Layer* layer) {
1667 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001668 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001669 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001670 recordBufferingStats(layer->getName().string(),
1671 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001672 }
Robert Carr2047fae2016-11-28 14:09:09 -08001673 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001674
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001675 if (presentFenceTime->isValid()) {
1676 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001677 enableHardwareVsync();
1678 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001679 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001680 }
1681 }
1682
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001683 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001684 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001685 enableHardwareVsync();
1686 }
1687 }
1688
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001689 if (mAnimCompositionPending) {
1690 mAnimCompositionPending = false;
1691
Brian Anderson4e606e32017-03-16 15:34:57 -07001692 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001693 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001694 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001695 } else {
1696 // The HWC doesn't support present fences, so use the refresh
1697 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001698 nsecs_t presentTime =
1699 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001700 mAnimFrameTracker.setActualPresentTime(presentTime);
1701 }
1702 mAnimFrameTracker.advanceFrame();
1703 }
Dan Stozab90cf072015-03-05 11:05:59 -08001704
1705 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1706 return;
1707 }
1708
1709 nsecs_t currentTime = systemTime();
1710 if (mHasPoweredOff) {
1711 mHasPoweredOff = false;
1712 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001713 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001714 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001715 if (numPeriods < NUM_BUCKETS - 1) {
1716 mFrameBuckets[numPeriods] += elapsedTime;
1717 } else {
1718 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1719 }
1720 mTotalTime += elapsedTime;
1721 }
1722 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001723}
1724
1725void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001726 ATRACE_CALL();
1727 ALOGV("rebuildLayerStacks");
1728
Mathias Agopiancd60f992012-08-16 16:28:27 -07001729 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001730 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1731 ATRACE_CALL();
1732 mVisibleRegionsDirty = false;
1733 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001734
Jeff Sharkey76488112017-02-27 14:15:18 -07001735 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1736 Region opaqueRegion;
1737 Region dirtyRegion;
1738 Vector<sp<Layer>> layersSortedByZ;
1739 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1740 const Transform& tr(displayDevice->getTransform());
1741 const Rect bounds(displayDevice->getBounds());
1742 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001743 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001744
Jeff Sharkey76488112017-02-27 14:15:18 -07001745 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001746 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1747 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001748 Region drawRegion(tr.transform(
1749 layer->visibleNonTransparentRegion));
1750 drawRegion.andSelf(bounds);
1751 if (!drawRegion.isEmpty()) {
1752 layersSortedByZ.add(layer);
1753 } else {
1754 // Clear out the HWC layer if this layer was
1755 // previously visible, but no longer is
Steven Thomasb02664d2017-07-26 18:48:28 -07001756 layer->destroyHwcLayer(
1757 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001758 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001759 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001760 // WM changes displayDevice->layerStack upon sleep/awake.
1761 // Here we make sure we delete the HWC layers even if
1762 // WM changed their layer stack.
Steven Thomasb02664d2017-07-26 18:48:28 -07001763 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001764 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001765 });
1766 }
1767 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1768 displayDevice->undefinedRegion.set(bounds);
1769 displayDevice->undefinedRegion.subtractSelf(
1770 tr.transform(opaqueRegion));
1771 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001772 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001773 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001774}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001775
Romain Guy0147a172017-06-01 13:53:56 -07001776mat4 SurfaceFlinger::computeSaturationMatrix() const {
1777 if (mSaturation == 1.0f) {
1778 return mat4();
1779 }
1780
1781 // Rec.709 luma coefficients
1782 float3 luminance{0.213f, 0.715f, 0.072f};
1783 luminance *= 1.0f - mSaturation;
1784 return mat4(
1785 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1786 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1787 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1788 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1789 );
1790}
1791
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001792// pickColorMode translates a given dataspace into the best available color mode.
1793// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001794android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001795 switch (dataSpace) {
1796 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1797 // system expects.
1798 case HAL_DATASPACE_UNKNOWN:
1799 case HAL_DATASPACE_SRGB:
1800 case HAL_DATASPACE_V0_SRGB:
1801 return HAL_COLOR_MODE_SRGB;
1802 break;
1803
1804 case HAL_DATASPACE_DISPLAY_P3:
1805 return HAL_COLOR_MODE_DISPLAY_P3;
1806 break;
1807
1808 default:
1809 // TODO (courtneygo): Do we want to assert an error here?
1810 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1811 dataSpace);
1812 return HAL_COLOR_MODE_SRGB;
1813 break;
1814 }
1815}
1816
Romain Guy0147a172017-06-01 13:53:56 -07001817android_dataspace SurfaceFlinger::bestTargetDataSpace(
1818 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001819 // Only support sRGB and Display-P3 right now.
1820 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1821 return HAL_DATASPACE_DISPLAY_P3;
1822 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001823 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1824 return HAL_DATASPACE_DISPLAY_P3;
1825 }
1826 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1827 return HAL_DATASPACE_DISPLAY_P3;
1828 }
1829
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001830 return HAL_DATASPACE_V0_SRGB;
1831}
1832
Mathias Agopiancd60f992012-08-16 16:28:27 -07001833void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001834 ATRACE_CALL();
1835 ALOGV("setUpHWComposer");
1836
Jesse Hall028dc8f2013-08-20 16:35:32 -07001837 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001838 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1839 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1840 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1841
1842 // If nothing has changed (!dirty), don't recompose.
1843 // If something changed, but we don't currently have any visible layers,
1844 // and didn't when we last did a composition, then skip it this time.
1845 // The second rule does two things:
1846 // - When all layers are removed from a display, we'll emit one black
1847 // frame, then nothing more until we get new layers.
1848 // - When a display is created with a private layer stack, we won't
1849 // emit any black frames until a layer is added to the layer stack.
1850 bool mustRecompose = dirty && !(empty && wasEmpty);
1851
1852 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1853 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1854 mustRecompose ? "doing" : "skipping",
1855 dirty ? "+" : "-",
1856 empty ? "+" : "-",
1857 wasEmpty ? "+" : "-");
1858
Dan Stoza71433162014-02-04 16:22:36 -08001859 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001860
1861 if (mustRecompose) {
1862 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1863 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001864 }
1865
Dan Stoza9e56aa02015-11-02 13:00:03 -08001866 // build the h/w work list
1867 if (CC_UNLIKELY(mGeometryInvalid)) {
1868 mGeometryInvalid = false;
1869 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1870 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1871 const auto hwcId = displayDevice->getHwcDisplayId();
1872 if (hwcId >= 0) {
1873 const Vector<sp<Layer>>& currentLayers(
1874 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001875 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001876 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001877 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001878 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001879 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001880 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001881 }
1882 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001883
Robert Carrae060832016-11-28 10:51:00 -08001884 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001885 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001887 }
1888 }
1889 }
1890 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 }
Riley Andrews03414a12014-07-01 14:22:59 -07001892
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001893
Romain Guy0147a172017-06-01 13:53:56 -07001894 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001895
Dan Stoza9e56aa02015-11-02 13:00:03 -08001896 // Set the per-frame data
1897 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1898 auto& displayDevice = mDisplays[displayId];
1899 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001900
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 if (hwcId < 0) {
1902 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001903 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001904 if (colorMatrix != mPreviousColorMatrix) {
1905 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1906 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1907 "display %zd: %d", displayId, result);
1908 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001909 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1910 layer->setPerFrameData(displayDevice);
1911 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001912
1913 if (hasWideColorDisplay) {
1914 android_color_mode newColorMode;
1915 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1916
1917 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1918 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1919 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1920 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1921 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1922 }
1923 newColorMode = pickColorMode(newDataSpace);
1924
Thierry Strudel2924d012017-08-14 15:19:37 -07001925 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001926 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001927 }
1928
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001929 mPreviousColorMatrix = colorMatrix;
1930
Dan Stoza9e56aa02015-11-02 13:00:03 -08001931 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001932 auto& displayDevice = mDisplays[displayId];
1933 if (!displayDevice->isDisplayOn()) {
1934 continue;
1935 }
1936
1937 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1939 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001940 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001941}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001942
Mathias Agopiancd60f992012-08-16 16:28:27 -07001943void SurfaceFlinger::doComposition() {
1944 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001945 ALOGV("doComposition");
1946
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001947 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001948 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001949 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001950 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001951 // transform the dirty region into this screen's coordinate space
1952 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001953
1954 // repaint the framebuffer (if needed)
1955 doDisplayComposition(hw, dirtyRegion);
1956
Mathias Agopiancd60f992012-08-16 16:28:27 -07001957 hw->dirtyRegion.clear();
1958 hw->flip(hw->swapRegion);
1959 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001960 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001961 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001962 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001963}
1964
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001965void SurfaceFlinger::postFramebuffer()
1966{
Mathias Agopian841cde52012-03-01 15:44:37 -08001967 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001968 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001969
Mathias Agopiana44b0412011-10-16 18:46:35 -07001970 const nsecs_t now = systemTime();
1971 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001972
Dan Stoza9e56aa02015-11-02 13:00:03 -08001973 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1974 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001975 if (!displayDevice->isDisplayOn()) {
1976 continue;
1977 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001978 const auto hwcId = displayDevice->getHwcDisplayId();
1979 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001980 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001981 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001982 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001983 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1985 sp<Fence> releaseFence = Fence::NO_FENCE;
1986 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1987 releaseFence = displayDevice->getClientTargetAcquireFence();
1988 } else {
1989 auto hwcLayer = layer->getHwcLayer(hwcId);
1990 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001991 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 layer->onLayerDisplayed(releaseFence);
1993 }
1994 if (hwcId >= 0) {
1995 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001996 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001997 }
1998
Mathias Agopiana44b0412011-10-16 18:46:35 -07001999 mLastSwapBufferTime = systemTime() - now;
2000 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002001
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002002 // |mStateLock| not needed as we are on the main thread
2003 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002004 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2005 logFrameStats();
2006 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002007}
2008
Mathias Agopian87baae12012-07-31 12:38:26 -07002009void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002010{
Mathias Agopian841cde52012-03-01 15:44:37 -08002011 ATRACE_CALL();
2012
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002013 // here we keep a copy of the drawing state (that is the state that's
2014 // going to be overwritten by handleTransactionLocked()) outside of
2015 // mStateLock so that the side-effects of the State assignment
2016 // don't happen with mStateLock held (which can cause deadlocks).
2017 State drawingState(mDrawingState);
2018
Mathias Agopianca4d3602011-05-19 15:38:14 -07002019 Mutex::Autolock _l(mStateLock);
2020 const nsecs_t now = systemTime();
2021 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002022
Mathias Agopianca4d3602011-05-19 15:38:14 -07002023 // Here we're guaranteed that some transaction flags are set
2024 // so we can call handleTransactionLocked() unconditionally.
2025 // We call getTransactionFlags(), which will also clear the flags,
2026 // with mStateLock held to guarantee that mCurrentState won't change
2027 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002028
Mathias Agopiane57f2922012-08-09 16:29:12 -07002029 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002030 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002031
Mathias Agopianca4d3602011-05-19 15:38:14 -07002032 mLastTransactionTime = systemTime() - now;
2033 mDebugInTransaction = 0;
2034 invalidateHwcGeometry();
2035 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002036}
2037
Mathias Agopian87baae12012-07-31 12:38:26 -07002038void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002039{
Dan Stoza7dde5992015-05-22 09:51:44 -07002040 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002041 mCurrentState.traverseInZOrder([](Layer* layer) {
2042 layer->notifyAvailableFrames();
2043 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002044
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002045 /*
2046 * Traversal of the children
2047 * (perform the transaction for each of them if needed)
2048 */
2049
Mathias Agopian3559b072012-08-15 13:46:03 -07002050 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002051 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002052 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002053 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002054
2055 const uint32_t flags = layer->doTransaction(0);
2056 if (flags & Layer::eVisibleRegion)
2057 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002058 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002059 }
2060
2061 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002062 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002063 */
2064
Mathias Agopiane57f2922012-08-09 16:29:12 -07002065 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002066 // here we take advantage of Vector's copy-on-write semantics to
2067 // improve performance by skipping the transaction entirely when
2068 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002069 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2070 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002071 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002072 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002073 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002074 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002075
2076 // find the displays that were removed
2077 // (ie: in drawing state but not in current state)
2078 // also handle displays that changed
2079 // (ie: displays that are in both lists)
2080 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002081 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2082 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002083 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002084 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002085 // Call makeCurrent() on the primary display so we can
2086 // be sure that nothing associated with this display
2087 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002088 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002089 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002090 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002091 if (hw != NULL)
2092 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002093 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002094 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002095 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002096 } else {
2097 ALOGW("trying to remove the main display");
2098 }
2099 } else {
2100 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002101 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002102 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002103 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2104 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002105 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002106 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002107 // recreating the DisplayDevice, so we just remove it
2108 // from the drawing state, so that it get re-added
2109 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002110 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002111 if (hw != NULL)
2112 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002113 mDisplays.removeItem(display);
2114 mDrawingState.displays.removeItemsAt(i);
2115 dc--; i--;
2116 // at this point we must loop to the next item
2117 continue;
2118 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002119
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002120 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002121 if (disp != NULL) {
2122 if (state.layerStack != draw[i].layerStack) {
2123 disp->setLayerStack(state.layerStack);
2124 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002125 if ((state.orientation != draw[i].orientation)
2126 || (state.viewport != draw[i].viewport)
2127 || (state.frame != draw[i].frame))
2128 {
2129 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002130 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002131 }
Michael Lentine47e45402014-07-18 15:34:25 -07002132 if (state.width != draw[i].width || state.height != draw[i].height) {
2133 disp->setDisplaySize(state.width, state.height);
2134 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002135 }
2136 }
2137 }
2138
2139 // find displays that were added
2140 // (ie: in current state but not in drawing state)
2141 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002142 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002143 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002144
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002145 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002146 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002147 sp<IGraphicBufferProducer> bqProducer;
2148 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002149 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002150
Dan Stoza9e56aa02015-11-02 13:00:03 -08002151 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002152 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002153 // Virtual displays without a surface are dormant:
2154 // they have external state (layer stack, projection,
2155 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002156 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002157
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002158 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002159 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002160 int width = 0;
2161 int status = state.surface->query(
2162 NATIVE_WINDOW_WIDTH, &width);
2163 ALOGE_IF(status != NO_ERROR,
2164 "Unable to query width (%d)", status);
2165 int height = 0;
2166 status = state.surface->query(
2167 NATIVE_WINDOW_HEIGHT, &height);
2168 ALOGE_IF(status != NO_ERROR,
2169 "Unable to query height (%d)", status);
2170 int intFormat = 0;
2171 status = state.surface->query(
2172 NATIVE_WINDOW_FORMAT, &intFormat);
2173 ALOGE_IF(status != NO_ERROR,
2174 "Unable to query format (%d)", status);
2175 auto format = static_cast<android_pixel_format_t>(
2176 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002177
Dan Stoza8cf150a2016-08-02 10:27:31 -07002178 mHwc->allocateVirtualDisplay(width, height, &format,
2179 &hwcId);
2180 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002181
Dan Stoza5cf424b2016-05-20 14:02:39 -07002182 // TODO: Plumb requested format back up to consumer
2183
Dan Stoza9e56aa02015-11-02 13:00:03 -08002184 sp<VirtualDisplaySurface> vds =
2185 new VirtualDisplaySurface(*mHwc,
2186 hwcId, state.surface, bqProducer,
2187 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002188
2189 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002190 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002191 }
2192 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002193 ALOGE_IF(state.surface!=NULL,
2194 "adding a supported display, but rendering "
2195 "surface is provided (%p), ignoring it",
2196 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002197
2198 hwcId = state.type;
2199 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2200 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002201 }
2202
2203 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002204 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002205 sp<DisplayDevice> hw =
2206 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2207 dispSurface, producer,
2208 mRenderEngine->getEGLConfig(),
2209 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002210 hw->setLayerStack(state.layerStack);
2211 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002212 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002213 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002214 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002215 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002216 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002217 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002218 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002219 }
2220 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002221 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002222 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002223
Mathias Agopian84300952012-11-21 16:02:13 -08002224 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2225 // The transform hint might have changed for some layers
2226 // (either because a display has changed, or because a layer
2227 // as changed).
2228 //
2229 // Walk through all the layers in currentLayers,
2230 // and update their transform hint.
2231 //
2232 // If a layer is visible only on a single display, then that
2233 // display is used to calculate the hint, otherwise we use the
2234 // default display.
2235 //
2236 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2237 // the hint is set before we acquire a buffer from the surface texture.
2238 //
2239 // NOTE: layer transactions have taken place already, so we use their
2240 // drawing state. However, SurfaceFlinger's own transaction has not
2241 // happened yet, so we must use the current state layer list
2242 // (soon to become the drawing state list).
2243 //
2244 sp<const DisplayDevice> disp;
2245 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002246 bool first = true;
2247 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002248 // NOTE: we rely on the fact that layers are sorted by
2249 // layerStack first (so we don't have to traverse the list
2250 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002251 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002252 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002253 currentlayerStack = layerStack;
2254 // figure out if this layerstack is mirrored
2255 // (more than one display) if so, pick the default display,
2256 // if not, pick the only display it's on.
2257 disp.clear();
2258 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2259 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002260 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002261 if (disp == NULL) {
2262 disp = hw;
2263 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002264 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002265 break;
2266 }
2267 }
2268 }
2269 }
Chet Haase91d25932013-04-11 15:24:55 -07002270 if (disp == NULL) {
2271 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2272 // redraw after transform hint changes. See bug 8508397.
2273
2274 // could be null when this layer is using a layerStack
2275 // that is not visible on any display. Also can occur at
2276 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002277 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002278 }
Chet Haase91d25932013-04-11 15:24:55 -07002279 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002280
2281 first = false;
2282 });
Mathias Agopian84300952012-11-21 16:02:13 -08002283 }
2284
2285
Mathias Agopian3559b072012-08-15 13:46:03 -07002286 /*
2287 * Perform our own transaction if needed
2288 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002289
2290 if (mLayersAdded) {
2291 mLayersAdded = false;
2292 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002293 mVisibleRegionsDirty = true;
2294 }
2295
2296 // some layers might have been removed, so
2297 // we need to update the regions they're exposing.
2298 if (mLayersRemoved) {
2299 mLayersRemoved = false;
2300 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002301 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002302 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002303 // this layer is not visible anymore
2304 // TODO: we could traverse the tree from front to back and
2305 // compute the actual visible region
2306 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002307 Region visibleReg;
2308 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002309 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002310 }
Robert Carr2047fae2016-11-28 14:09:09 -08002311 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002312 }
2313
2314 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002315
2316 updateCursorAsync();
2317}
2318
2319void SurfaceFlinger::updateCursorAsync()
2320{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002321 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2322 auto& displayDevice = mDisplays[displayId];
2323 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002324 continue;
2325 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002326
2327 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2328 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002329 }
2330 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002331}
2332
2333void SurfaceFlinger::commitTransaction()
2334{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002335 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002336 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002337 for (const auto& l : mLayersPendingRemoval) {
2338 recordBufferingStats(l->getName().string(),
2339 l->getOccupancyHistory(true));
2340 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002341 }
2342 mLayersPendingRemoval.clear();
2343 }
2344
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002345 // If this transaction is part of a window animation then the next frame
2346 // we composite should be considered an animation as well.
2347 mAnimCompositionPending = mAnimTransactionPending;
2348
Mathias Agopian4fec8732012-06-29 14:12:52 -07002349 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002350 mDrawingState.traverseInZOrder([](Layer* layer) {
2351 layer->commitChildList();
2352 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002353 mTransactionPending = false;
2354 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002355 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356}
2357
Chia-I Wuab0c3192017-08-01 11:29:00 -07002358void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002359 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002360{
Mathias Agopian841cde52012-03-01 15:44:37 -08002361 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002362 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364 Region aboveOpaqueLayers;
2365 Region aboveCoveredLayers;
2366 Region dirty;
2367
Mathias Agopian87baae12012-07-31 12:38:26 -07002368 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369
Robert Carr2047fae2016-11-28 14:09:09 -08002370 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002371 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002372 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002373
Jesse Hall01e29052013-02-19 16:13:35 -08002374 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002375 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002376 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002377
Mathias Agopianab028732010-03-16 16:41:46 -07002378 /*
2379 * opaqueRegion: area of a surface that is fully opaque.
2380 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002381 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002382
2383 /*
2384 * visibleRegion: area of a surface that is visible on screen
2385 * and not fully transparent. This is essentially the layer's
2386 * footprint minus the opaque regions above it.
2387 * Areas covered by a translucent surface are considered visible.
2388 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002389 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002390
2391 /*
2392 * coveredRegion: area of a surface that is covered by all
2393 * visible regions above it (which includes the translucent areas).
2394 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002395 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002396
Jesse Halla8026d22012-09-25 13:25:04 -07002397 /*
2398 * transparentRegion: area of a surface that is hinted to be completely
2399 * transparent. This is only used to tell when the layer has no visible
2400 * non-transparent regions and can be removed from the layer list. It
2401 * does not affect the visibleRegion of this layer or any layers
2402 * beneath it. The hint may not be correct if apps don't respect the
2403 * SurfaceView restrictions (which, sadly, some don't).
2404 */
2405 Region transparentRegion;
2406
Mathias Agopianab028732010-03-16 16:41:46 -07002407
2408 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002409 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002410 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002411 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002412 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002413 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002414 if (!visibleRegion.isEmpty()) {
2415 // Remove the transparent area from the visible region
2416 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002417 if (tr.preserveRects()) {
2418 // transform the transparent region
2419 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002420 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002421 // transformation too complex, can't do the
2422 // transparent region optimization.
2423 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002424 }
Mathias Agopianab028732010-03-16 16:41:46 -07002425 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002426
Mathias Agopianab028732010-03-16 16:41:46 -07002427 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002428 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002429 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002430 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2431 // the opaque region is the layer's footprint
2432 opaqueRegion = visibleRegion;
2433 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002434 }
2435 }
2436
Mathias Agopianab028732010-03-16 16:41:46 -07002437 // Clip the covered region to the visible region
2438 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2439
2440 // Update aboveCoveredLayers for next (lower) layer
2441 aboveCoveredLayers.orSelf(visibleRegion);
2442
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002443 // subtract the opaque region covered by the layers above us
2444 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445
2446 // compute this layer's dirty region
2447 if (layer->contentDirty) {
2448 // we need to invalidate the whole region
2449 dirty = visibleRegion;
2450 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002451 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452 layer->contentDirty = false;
2453 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002454 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002455 * the exposed region consists of two components:
2456 * 1) what's VISIBLE now and was COVERED before
2457 * 2) what's EXPOSED now less what was EXPOSED before
2458 *
2459 * note that (1) is conservative, we start with the whole
2460 * visible region but only keep what used to be covered by
2461 * something -- which mean it may have been exposed.
2462 *
2463 * (2) handles areas that were not covered by anything but got
2464 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002465 */
Mathias Agopianab028732010-03-16 16:41:46 -07002466 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002467 const Region oldVisibleRegion = layer->visibleRegion;
2468 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002469 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2470 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002471 }
2472 dirty.subtractSelf(aboveOpaqueLayers);
2473
2474 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002475 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002476
Mathias Agopianab028732010-03-16 16:41:46 -07002477 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002478 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002479
Jesse Halla8026d22012-09-25 13:25:04 -07002480 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002481 layer->setVisibleRegion(visibleRegion);
2482 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002483 layer->setVisibleNonTransparentRegion(
2484 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002485 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486
Mathias Agopian87baae12012-07-31 12:38:26 -07002487 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002488}
2489
Chia-I Wuab0c3192017-08-01 11:29:00 -07002490void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002491 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002492 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002493 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002494 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002495 }
2496 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002497}
2498
Dan Stoza6b9454d2014-11-07 16:00:59 -08002499bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002501 ALOGV("handlePageFlip");
2502
Brian Andersond6927fb2016-07-23 23:37:30 -07002503 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504
Mathias Agopian4fec8732012-06-29 14:12:52 -07002505 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002506 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002507 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002508
2509 // Store the set of layers that need updates. This set must not change as
2510 // buffers are being latched, as this could result in a deadlock.
2511 // Example: Two producers share the same command stream and:
2512 // 1.) Layer 0 is latched
2513 // 2.) Layer 0 gets a new frame
2514 // 2.) Layer 1 gets a new frame
2515 // 3.) Layer 1 is latched.
2516 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2517 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002518 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002519 if (layer->hasQueuedFrame()) {
2520 frameQueued = true;
2521 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002522 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002523 } else {
2524 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002525 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002526 } else {
2527 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002528 }
Robert Carr2047fae2016-11-28 14:09:09 -08002529 });
2530
Dan Stoza9e56aa02015-11-02 13:00:03 -08002531 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002532 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002533 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002534 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002535 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002536 newDataLatched = true;
2537 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002538 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002539
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002540 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002541
2542 // If we will need to wake up at some time in the future to deal with a
2543 // queued frame that shouldn't be displayed during this vsync period, wake
2544 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002545 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002546 signalLayerUpdate();
2547 }
2548
2549 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002550 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551}
2552
Mathias Agopianad456f92011-01-13 17:53:01 -08002553void SurfaceFlinger::invalidateHwcGeometry()
2554{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002555 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002556}
2557
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002558
Fabien Sanglard830b8472016-11-30 16:35:58 -08002559void SurfaceFlinger::doDisplayComposition(
2560 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002561 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562{
Dan Stoza71433162014-02-04 16:22:36 -08002563 // We only need to actually compose the display if:
2564 // 1) It is being handled by hardware composer, which may need this to
2565 // keep its virtual display state machine in sync, or
2566 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002567 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002568 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002569 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002570 return;
2571 }
2572
Dan Stoza9e56aa02015-11-02 13:00:03 -08002573 ALOGV("doDisplayComposition");
2574
Mathias Agopian87baae12012-07-31 12:38:26 -07002575 Region dirtyRegion(inDirtyRegion);
2576
Mathias Agopianb8a55602009-06-26 19:06:36 -07002577 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002578 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579
Fabien Sanglard830b8472016-11-30 16:35:58 -08002580 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002581 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002582 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2583 // takes a rectangle, we must make sure to update that whole
2584 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002585 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002586 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002587 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002588 // We need to redraw the rectangle that will be updated
2589 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002590 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002591 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002592 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002593 } else {
2594 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002595 dirtyRegion.set(displayDevice->bounds());
2596 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597 }
2598 }
2599
Fabien Sanglard830b8472016-11-30 16:35:58 -08002600 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002602 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002603 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002604
2605 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002606 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607}
2608
Dan Stoza9e56aa02015-11-02 13:00:03 -08002609bool SurfaceFlinger::doComposeSurfaces(
2610 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002611{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002612 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002613
Dan Stoza9e56aa02015-11-02 13:00:03 -08002614 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002615
2616 mat4 oldColorMatrix;
2617 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2618 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2619 if (applyColorMatrix) {
2620 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2621 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2622 }
2623
Dan Stoza9e56aa02015-11-02 13:00:03 -08002624 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2625 if (hasClientComposition) {
2626 ALOGV("hasClientComposition");
2627
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002628#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002629 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002630 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002631#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002632 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002633 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002634 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002635 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002636
2637 // |mStateLock| not needed as we are on the main thread
2638 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002639 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2640 }
2641 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002642 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002643
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002644 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002645 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2646 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002647 // when using overlays, we assume a fully transparent framebuffer
2648 // NOTE: we could reduce how much we need to clear, for instance
2649 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002650 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002651 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002652 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002653 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002654 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002655 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002656
2657 // we remove the scissor part
2658 // we're left with the letterbox region
2659 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002660 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002661
2662 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002664
2665 // but limit it to the dirty region
2666 region.andSelf(dirty);
2667
Mathias Agopianb9494d52012-04-18 02:28:45 -07002668 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002669 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002670 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002672 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002673 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002674
Dan Stoza9e56aa02015-11-02 13:00:03 -08002675 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002676 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002677 // scissor on the main display. It should never be needed
2678 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002679 const Rect& bounds(displayDevice->getBounds());
2680 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002681 if (scissor != bounds) {
2682 // scissor doesn't match the screen's dimensions, so we
2683 // need to clear everything outside of it and enable
2684 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002685
Mathias Agopianf45c5102012-10-24 16:29:17 -07002686 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002687 const uint32_t height = displayDevice->getHeight();
2688 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002689 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002690 }
2691 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002692 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002693
Mathias Agopian85d751c2012-08-29 16:59:24 -07002694 /*
2695 * and then, render the layers targeted at the framebuffer
2696 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002697
Dan Stoza9e56aa02015-11-02 13:00:03 -08002698 ALOGV("Rendering client layers");
2699 const Transform& displayTransform = displayDevice->getTransform();
2700 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002701 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002702 bool firstLayer = true;
2703 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2704 const Region clip(dirty.intersect(
2705 displayTransform.transform(layer->visibleRegion)));
2706 ALOGV("Layer: %s", layer->getName().string());
2707 ALOGV(" Composition type: %s",
2708 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002709 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002710 switch (layer->getCompositionType(hwcId)) {
2711 case HWC2::Composition::Cursor:
2712 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002713 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002714 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002715 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002716 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2717 layer->isOpaque(state) && (state.alpha == 1.0f)
2718 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002719 // never clear the very first layer since we're
2720 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002721 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002722 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002723 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002724 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002725 case HWC2::Composition::Client: {
2726 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002727 break;
2728 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002729 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002730 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002731 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002732 } else {
2733 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002734 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002735 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002736 }
2737 } else {
2738 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002739 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002740 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002741 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002742 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002743 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002744 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002745 }
2746 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002747
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002748 if (applyColorMatrix) {
2749 getRenderEngine().setupColorTransform(oldColorMatrix);
2750 }
2751
Mathias Agopianf45c5102012-10-24 16:29:17 -07002752 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002753 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002754 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755}
2756
Fabien Sanglard830b8472016-11-30 16:35:58 -08002757void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2758 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002759 RenderEngine& engine(getRenderEngine());
2760 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761}
2762
Dan Stoza7d89d062015-04-30 13:29:25 -07002763status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002764 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002765 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002766 const sp<Layer>& lbc,
2767 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002768{
Dan Stoza7d89d062015-04-30 13:29:25 -07002769 // add this layer to the current state list
2770 {
2771 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002772 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002773 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2774 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002775 return NO_MEMORY;
2776 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002777 if (parent == nullptr) {
2778 mCurrentState.layersSortedByZ.add(lbc);
2779 } else {
chaviwc9674332017-08-28 12:32:18 -07002780 bool found = false;
2781 mCurrentState.traverseInZOrder([&](Layer* layer) {
2782 if (layer == parent.get()) {
2783 found = true;
2784 }
2785 });
2786
2787 if (!found) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002788 ALOGE("addClientLayer called with a removed parent");
2789 return NAME_NOT_FOUND;
2790 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002791 parent->addChild(lbc);
2792 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002793
Dan Stoza7d89d062015-04-30 13:29:25 -07002794 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002795 mLayersAdded = true;
2796 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002797 }
2798
Mathias Agopian96f08192010-06-02 23:28:45 -07002799 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002800 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002801
Dan Stoza7d89d062015-04-30 13:29:25 -07002802 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002803}
2804
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002805status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002806 Mutex::Autolock _l(mStateLock);
2807
Robert Carr1f0a16a2016-10-24 16:27:39 -07002808 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002809 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002810 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002811 if (topLevelOnly) {
2812 return NO_ERROR;
2813 }
2814
Chia-I Wu98f1c102017-05-30 14:54:08 -07002815 sp<Layer> ancestor = p;
2816 while (ancestor->getParent() != nullptr) {
2817 ancestor = ancestor->getParent();
2818 }
2819 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2820 ALOGE("removeLayer called with a layer whose parent has been removed");
2821 return NAME_NOT_FOUND;
2822 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002823
2824 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002825 } else {
2826 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002827 }
2828
Robert Carr136e2f62017-02-08 17:54:29 -08002829 // As a matter of normal operation, the LayerCleaner will produce a second
2830 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2831 // so we will succeed in promoting it, but it's already been removed
2832 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2833 // otherwise something has gone wrong and we are leaking the layer.
2834 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002835 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2836 layer->getName().string(),
2837 (p != nullptr) ? p->getName().string() : "no-parent");
2838 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002839 } else if (index < 0) {
2840 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002841 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002842
Chia-I Wuc6657022017-08-15 11:18:17 -07002843 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002844 mLayersPendingRemoval.add(layer);
2845 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002846 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002847 setTransactionFlags(eTransactionNeeded);
2848 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849}
2850
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002851uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002852 return android_atomic_release_load(&mTransactionFlags);
2853}
2854
Mathias Agopian3f844832013-08-07 21:24:32 -07002855uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2857}
2858
Mathias Agopian3f844832013-08-07 21:24:32 -07002859uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2861 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002862 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863 }
2864 return old;
2865}
2866
Mathias Agopian8b33f032012-07-24 20:43:54 -07002867void SurfaceFlinger::setTransactionState(
2868 const Vector<ComposerState>& state,
2869 const Vector<DisplayState>& displays,
2870 uint32_t flags)
2871{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002872 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002873 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002874 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002875
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002876 if (flags & eAnimation) {
2877 // For window updates that are part of an animation we must wait for
2878 // previous animation "frames" to be handled.
2879 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002880 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002881 if (CC_UNLIKELY(err != NO_ERROR)) {
2882 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002883 // caller after a few seconds.
2884 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2885 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002886 mAnimTransactionPending = false;
2887 break;
2888 }
2889 }
2890 }
2891
Mathias Agopiane57f2922012-08-09 16:29:12 -07002892 size_t count = displays.size();
2893 for (size_t i=0 ; i<count ; i++) {
2894 const DisplayState& s(displays[i]);
2895 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002896 }
2897
Mathias Agopiane57f2922012-08-09 16:29:12 -07002898 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002899 for (size_t i=0 ; i<count ; i++) {
2900 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002901 // Here we need to check that the interface we're given is indeed
2902 // one of our own. A malicious client could give us a NULL
2903 // IInterface, or one of its own or even one of our own but a
2904 // different type. All these situations would cause us to crash.
2905 //
2906 // NOTE: it would be better to use RTTI as we could directly check
2907 // that we have a Client*. however, RTTI is disabled in Android.
2908 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002909 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002910 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002911 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002912 sp<Client> client( static_cast<Client *>(s.client.get()) );
2913 transactionFlags |= setClientStateLocked(client, s.state);
2914 }
2915 }
2916 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002917 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002918
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002919 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2920 // anyway. This can be used as a flush mechanism for previous async transactions.
2921 // Empty animation transaction can be used to simulate back-pressure, so also force a
2922 // transaction for empty animation transactions.
2923 if (transactionFlags == 0 &&
2924 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002925 transactionFlags = eTransactionNeeded;
2926 }
2927
Mathias Agopian386aa982011-11-07 21:58:03 -08002928 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002929 if (mInterceptor.isEnabled()) {
2930 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2931 }
Irvel468051e2016-06-13 16:44:44 -07002932
Mathias Agopian386aa982011-11-07 21:58:03 -08002933 // this triggers the transaction
2934 setTransactionFlags(transactionFlags);
2935
2936 // if this is a synchronous transaction, wait for it to take effect
2937 // before returning.
2938 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002939 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002940 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002941 if (flags & eAnimation) {
2942 mAnimTransactionPending = true;
2943 }
2944 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002945 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2946 if (CC_UNLIKELY(err != NO_ERROR)) {
2947 // just in case something goes wrong in SF, return to the
2948 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002949 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2950 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002951 break;
2952 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002953 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002954 }
2955}
2956
Mathias Agopiane57f2922012-08-09 16:29:12 -07002957uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2958{
Jesse Hall9a143922012-10-04 16:29:19 -07002959 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2960 if (dpyIdx < 0)
2961 return 0;
2962
Mathias Agopiane57f2922012-08-09 16:29:12 -07002963 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002964 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002965 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002966 const uint32_t what = s.what;
2967 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002968 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002969 disp.surface = s.surface;
2970 flags |= eDisplayTransactionNeeded;
2971 }
2972 }
2973 if (what & DisplayState::eLayerStackChanged) {
2974 if (disp.layerStack != s.layerStack) {
2975 disp.layerStack = s.layerStack;
2976 flags |= eDisplayTransactionNeeded;
2977 }
2978 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002979 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002980 if (disp.orientation != s.orientation) {
2981 disp.orientation = s.orientation;
2982 flags |= eDisplayTransactionNeeded;
2983 }
2984 if (disp.frame != s.frame) {
2985 disp.frame = s.frame;
2986 flags |= eDisplayTransactionNeeded;
2987 }
2988 if (disp.viewport != s.viewport) {
2989 disp.viewport = s.viewport;
2990 flags |= eDisplayTransactionNeeded;
2991 }
2992 }
Michael Lentine47e45402014-07-18 15:34:25 -07002993 if (what & DisplayState::eDisplaySizeChanged) {
2994 if (disp.width != s.width) {
2995 disp.width = s.width;
2996 flags |= eDisplayTransactionNeeded;
2997 }
2998 if (disp.height != s.height) {
2999 disp.height = s.height;
3000 flags |= eDisplayTransactionNeeded;
3001 }
3002 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003003 }
3004 return flags;
3005}
3006
3007uint32_t SurfaceFlinger::setClientStateLocked(
3008 const sp<Client>& client,
3009 const layer_state_t& s)
3010{
3011 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003012 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003013 if (layer != 0) {
3014 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003015 bool geometryAppliesWithResize =
3016 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003017 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003018 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003019 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003020 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003021 }
3022 if (what & layer_state_t::eLayerChanged) {
3023 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003024 const auto& p = layer->getParent();
3025 if (p == nullptr) {
3026 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3027 if (layer->setLayer(s.z) && idx >= 0) {
3028 mCurrentState.layersSortedByZ.removeAt(idx);
3029 mCurrentState.layersSortedByZ.add(layer);
3030 // we need traversal (state changed)
3031 // AND transaction (list changed)
3032 flags |= eTransactionNeeded|eTraversalNeeded;
3033 }
3034 } else {
3035 if (p->setChildLayer(layer, s.z)) {
3036 flags |= eTransactionNeeded|eTraversalNeeded;
3037 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003038 }
3039 }
Robert Carrdb66e622017-04-10 16:55:57 -07003040 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003041 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003042 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003043 mCurrentState.layersSortedByZ.removeAt(idx);
3044 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003045 flags |= eTransactionNeeded|eTraversalNeeded;
3046 }
3047 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003048 if (what & layer_state_t::eSizeChanged) {
3049 if (layer->setSize(s.w, s.h)) {
3050 flags |= eTraversalNeeded;
3051 }
3052 }
3053 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003054 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003055 flags |= eTraversalNeeded;
3056 }
3057 if (what & layer_state_t::eMatrixChanged) {
3058 if (layer->setMatrix(s.matrix))
3059 flags |= eTraversalNeeded;
3060 }
3061 if (what & layer_state_t::eTransparentRegionChanged) {
3062 if (layer->setTransparentRegionHint(s.transparentRegion))
3063 flags |= eTraversalNeeded;
3064 }
Dan Stoza23116082015-06-18 14:58:39 -07003065 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003066 if (layer->setFlags(s.flags, s.mask))
3067 flags |= eTraversalNeeded;
3068 }
3069 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003070 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003071 flags |= eTraversalNeeded;
3072 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003073 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003074 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003075 flags |= eTraversalNeeded;
3076 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003077 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003078 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003079 // We only allow setting layer stacks for top level layers,
3080 // everything else inherits layer stack from its parent.
3081 if (layer->hasParent()) {
3082 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3083 layer->getName().string());
3084 } else if (idx < 0) {
3085 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3086 "that also does not appear in the top level layer list. Something"
3087 " has gone wrong.", layer->getName().string());
3088 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003089 mCurrentState.layersSortedByZ.removeAt(idx);
3090 mCurrentState.layersSortedByZ.add(layer);
3091 // we need traversal (state changed)
3092 // AND transaction (list changed)
3093 flags |= eTransactionNeeded|eTraversalNeeded;
3094 }
3095 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003096 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003097 if (s.barrierHandle != nullptr) {
3098 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3099 } else if (s.barrierGbp != nullptr) {
3100 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3101 if (authenticateSurfaceTextureLocked(gbp)) {
3102 const auto& otherLayer =
3103 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3104 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3105 } else {
3106 ALOGE("Attempt to defer transaction to to an"
3107 " unrecognized GraphicBufferProducer");
3108 }
3109 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003110 // We don't trigger a traversal here because if no other state is
3111 // changed, we don't want this to cause any more work
3112 }
chaviw06178942017-07-27 10:25:59 -07003113 // Always re-parent the children that explicitly requested to get
3114 // re-parented before the general re-parent of all children.
3115 if (what & layer_state_t::eReparentChild) {
3116 if (layer->reparentChild(s.parentHandleForChild, s.childHandle)) {
3117 flags |= eTransactionNeeded|eTraversalNeeded;
3118 }
3119 }
Robert Carr1db73f62016-12-21 12:58:51 -08003120 if (what & layer_state_t::eReparentChildren) {
3121 if (layer->reparentChildren(s.reparentHandle)) {
3122 flags |= eTransactionNeeded|eTraversalNeeded;
3123 }
3124 }
Robert Carr9524cb32017-02-13 11:32:32 -08003125 if (what & layer_state_t::eDetachChildren) {
3126 layer->detachChildren();
3127 }
Robert Carrc3574f72016-03-24 12:19:32 -07003128 if (what & layer_state_t::eOverrideScalingModeChanged) {
3129 layer->setOverrideScalingMode(s.overrideScalingMode);
3130 // We don't trigger a traversal here because if no other state is
3131 // changed, we don't want this to cause any more work
3132 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003133 }
3134 return flags;
3135}
3136
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003137status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003138 const String8& name,
3139 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003140 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003141 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3142 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003144 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003145 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003146 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003147 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003148 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003149
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003150 status_t result = NO_ERROR;
3151
3152 sp<Layer> layer;
3153
Cody Northropbc755282017-03-31 12:00:08 -06003154 String8 uniqueName = getUniqueLayerName(name);
3155
Mathias Agopian3165cc22012-08-08 19:42:09 -07003156 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3157 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003158 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003159 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003160 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003161 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003162 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003163 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003164 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003165 handle, gbp, &layer);
3166 break;
3167 default:
3168 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169 break;
3170 }
3171
Dan Stoza7d89d062015-04-30 13:29:25 -07003172 if (result != NO_ERROR) {
3173 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003175
Chia-I Wuab0c3192017-08-01 11:29:00 -07003176 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3177 // TODO b/64227542
3178 if (windowType == 441731) {
3179 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3180 layer->setPrimaryDisplayOnly();
3181 }
3182
Albert Chaulk479c60c2017-01-27 14:21:34 -05003183 layer->setInfo(windowType, ownerUid);
3184
Robert Carr1f0a16a2016-10-24 16:27:39 -07003185 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003186 if (result != NO_ERROR) {
3187 return result;
3188 }
Irvelffc9efc2016-07-27 15:16:37 -07003189 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003190
3191 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003192 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193}
3194
Cody Northropbc755282017-03-31 12:00:08 -06003195String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3196{
3197 bool matchFound = true;
3198 uint32_t dupeCounter = 0;
3199
3200 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3201 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3202
3203 // Loop over layers until we're sure there is no matching name
3204 while (matchFound) {
3205 matchFound = false;
3206 mDrawingState.traverseInZOrder([&](Layer* layer) {
3207 if (layer->getName() == uniqueName) {
3208 matchFound = true;
3209 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3210 }
3211 });
3212 }
3213
3214 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3215
3216 return uniqueName;
3217}
3218
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003219status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3220 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3221 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222{
3223 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003224 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225 case PIXEL_FORMAT_TRANSPARENT:
3226 case PIXEL_FORMAT_TRANSLUCENT:
3227 format = PIXEL_FORMAT_RGBA_8888;
3228 break;
3229 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003230 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003231 break;
3232 }
3233
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003234 *outLayer = new Layer(this, client, name, w, h, flags);
3235 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3236 if (err == NO_ERROR) {
3237 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003238 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003240
3241 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3242 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003243}
3244
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003245status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3246 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3247 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003249 *outLayer = new LayerDim(this, client, name, w, h, flags);
3250 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003251 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003252 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003253}
3254
Mathias Agopianac9fa422013-02-11 16:40:36 -08003255status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003256{
Robert Carr9524cb32017-02-13 11:32:32 -08003257 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003258 status_t err = NO_ERROR;
3259 sp<Layer> l(client->getLayerUser(handle));
3260 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003261 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003262 err = removeLayer(l);
3263 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3264 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003265 }
3266 return err;
3267}
3268
Mathias Agopian13127d82013-03-05 17:47:11 -08003269status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003270{
Mathias Agopian67106042013-03-14 19:18:13 -07003271 // called by ~LayerCleaner() when all references to the IBinder (handle)
3272 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003273 sp<Layer> l = layer.promote();
3274 if (l == nullptr) {
3275 // The layer has already been removed, carry on
3276 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003277 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003278 // If we have a parent, then we can continue to live as long as it does.
3279 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003280}
3281
Mathias Agopianb60314a2012-04-10 22:09:54 -07003282// ---------------------------------------------------------------------------
3283
Andy McFadden13a082e2012-08-24 10:16:42 -07003284void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003285 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003286 Vector<ComposerState> state;
3287 Vector<DisplayState> displays;
3288 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003289 d.what = DisplayState::eDisplayProjectionChanged |
3290 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003291 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003292 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003293 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003294 d.frame.makeInvalid();
3295 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003296 d.width = 0;
3297 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003298 displays.add(d);
3299 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003300 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3301 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003302
Dan Stoza9e56aa02015-11-02 13:00:03 -08003303 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3304 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003305 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003306
Brian Andersond0010582017-03-07 13:20:31 -08003307 // Use phase of 0 since phase is not known.
3308 // Use latency of 0, which will snap to the ideal latency.
3309 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003310}
3311
3312void SurfaceFlinger::initializeDisplays() {
3313 class MessageScreenInitialized : public MessageBase {
3314 SurfaceFlinger* flinger;
3315 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003316 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003317 virtual bool handler() {
3318 flinger->onInitializeDisplays();
3319 return true;
3320 }
3321 };
3322 sp<MessageBase> msg = new MessageScreenInitialized(this);
3323 postMessageAsync(msg); // we may be called from main thread, use async message
3324}
3325
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003326void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003327 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003328 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3329 this);
3330 int32_t type = hw->getDisplayType();
3331 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003332
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003333 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003334 return;
3335 }
3336
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003337 hw->setPowerMode(mode);
3338 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3339 ALOGW("Trying to set power mode for virtual display");
3340 return;
3341 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003342
Irvelffc9efc2016-07-27 15:16:37 -07003343 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003344 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003345 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3346 if (idx < 0) {
3347 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3348 return;
3349 }
3350 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3351 }
3352
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003353 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003354 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003355 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003356 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3357 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003358 // FIXME: eventthread only knows about the main display right now
3359 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003360 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003361 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003362
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003363 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003364 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003365 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003366
3367 struct sched_param param = {0};
3368 param.sched_priority = 1;
3369 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3370 ALOGW("Couldn't set SCHED_FIFO on display on");
3371 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003372 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003373 // Turn off the display
3374 struct sched_param param = {0};
3375 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3376 ALOGW("Couldn't set SCHED_OTHER on display off");
3377 }
3378
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003379 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003380 disableHardwareVsync(true); // also cancels any in-progress resync
3381
Mathias Agopiancde87a32012-09-13 14:09:01 -07003382 // FIXME: eventthread only knows about the main display right now
3383 mEventThread->onScreenReleased();
3384 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003385
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003386 getHwComposer().setPowerMode(type, mode);
3387 mVisibleRegionsDirty = true;
3388 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003389 } else if (mode == HWC_POWER_MODE_DOZE ||
3390 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003391 // Update display while dozing
3392 getHwComposer().setPowerMode(type, mode);
3393 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3394 // FIXME: eventthread only knows about the main display right now
3395 mEventThread->onScreenAcquired();
3396 resyncToHardwareVsync(true);
3397 }
3398 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3399 // Leave display going to doze
3400 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3401 disableHardwareVsync(true); // also cancels any in-progress resync
3402 // FIXME: eventthread only knows about the main display right now
3403 mEventThread->onScreenReleased();
3404 }
3405 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003406 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003407 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003408 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003409 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003410}
3411
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003412void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3413 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003414 SurfaceFlinger& mFlinger;
3415 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003416 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003417 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003418 MessageSetPowerMode(SurfaceFlinger& flinger,
3419 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3420 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003421 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003422 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003423 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003424 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003425 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003426 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003427 ALOGW("Attempt to set power mode = %d for virtual display",
3428 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003429 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003430 mFlinger.setPowerModeInternal(
3431 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003432 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003433 return true;
3434 }
3435 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003436 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003437 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003438}
3439
3440// ---------------------------------------------------------------------------
3441
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003442status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3443{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003444 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003445
Mathias Agopianbd115332013-04-18 16:41:04 -07003446 IPCThreadState* ipc = IPCThreadState::self();
3447 const int pid = ipc->getCallingPid();
3448 const int uid = ipc->getCallingUid();
3449 if ((uid != AID_SHELL) &&
3450 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003451 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003452 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003453 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003454 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003455 // (this would indicate SF is stuck, but we want to be able to
3456 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003457 status_t err = mStateLock.timedLock(s2ns(1));
3458 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003459 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003460 result.appendFormat(
3461 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3462 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003463 }
3464
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003465 bool dumpAll = true;
3466 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003467 size_t numArgs = args.size();
3468 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003469 if ((index < numArgs) &&
3470 (args[index] == String16("--list"))) {
3471 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003472 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003473 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003474 }
3475
3476 if ((index < numArgs) &&
3477 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003478 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003479 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003480 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003481 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003482
3483 if ((index < numArgs) &&
3484 (args[index] == String16("--latency-clear"))) {
3485 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003486 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003487 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003488 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003489
3490 if ((index < numArgs) &&
3491 (args[index] == String16("--dispsync"))) {
3492 index++;
3493 mPrimaryDispSync.dump(result);
3494 dumpAll = false;
3495 }
Dan Stozab90cf072015-03-05 11:05:59 -08003496
3497 if ((index < numArgs) &&
3498 (args[index] == String16("--static-screen"))) {
3499 index++;
3500 dumpStaticScreenStats(result);
3501 dumpAll = false;
3502 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003503
3504 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003505 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003506 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003507 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003508 dumpAll = false;
3509 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003510
3511 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3512 index++;
3513 dumpWideColorInfo(result);
3514 dumpAll = false;
3515 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003517
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003518 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003519 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003520 }
3521
Mathias Agopian9795c422009-08-26 16:36:26 -07003522 if (locked) {
3523 mStateLock.unlock();
3524 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525 }
3526 write(fd, result.string(), result.size());
3527 return NO_ERROR;
3528}
3529
Dan Stozac7014012014-02-14 15:03:43 -08003530void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3531 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003532{
Robert Carr2047fae2016-11-28 14:09:09 -08003533 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003534 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003535 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003536}
3537
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003538void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003539 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003540{
3541 String8 name;
3542 if (index < args.size()) {
3543 name = String8(args[index]);
3544 index++;
3545 }
3546
Dan Stoza9e56aa02015-11-02 13:00:03 -08003547 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3548 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003549 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003550
3551 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003552 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003553 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003554 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003555 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003556 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003557 }
Robert Carr2047fae2016-11-28 14:09:09 -08003558 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003559 }
3560}
3561
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003562void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003563 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003564{
3565 String8 name;
3566 if (index < args.size()) {
3567 name = String8(args[index]);
3568 index++;
3569 }
3570
Robert Carr2047fae2016-11-28 14:09:09 -08003571 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003572 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003573 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003574 }
Robert Carr2047fae2016-11-28 14:09:09 -08003575 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003576
Svetoslavd85084b2014-03-20 10:28:31 -07003577 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003578}
3579
Jamie Gennis6547ff42013-07-16 20:12:42 -07003580// This should only be called from the main thread. Otherwise it would need
3581// the lock and should use mCurrentState rather than mDrawingState.
3582void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003583 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003584 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003585 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003586
3587 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3588}
3589
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003590void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003591{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003592 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003593 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3594
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003595 if (isLayerTripleBufferingDisabled())
3596 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003597
3598 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003599 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003600 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003601 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003602 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3603 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003604 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003605}
3606
Dan Stozab90cf072015-03-05 11:05:59 -08003607void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3608{
3609 result.appendFormat("Static screen stats:\n");
3610 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3611 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3612 float percent = 100.0f *
3613 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3614 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3615 b + 1, bucketTimeSec, percent);
3616 }
3617 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3618 float percent = 100.0f *
3619 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3620 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3621 NUM_BUCKETS - 1, bucketTimeSec, percent);
3622}
3623
Dan Stozae77c7662016-05-13 11:37:28 -07003624void SurfaceFlinger::recordBufferingStats(const char* layerName,
3625 std::vector<OccupancyTracker::Segment>&& history) {
3626 Mutex::Autolock lock(mBufferingStatsMutex);
3627 auto& stats = mBufferingStats[layerName];
3628 for (const auto& segment : history) {
3629 if (!segment.usedThirdBuffer) {
3630 stats.twoBufferTime += segment.totalTime;
3631 }
3632 if (segment.occupancyAverage < 1.0f) {
3633 stats.doubleBufferedTime += segment.totalTime;
3634 } else if (segment.occupancyAverage < 2.0f) {
3635 stats.tripleBufferedTime += segment.totalTime;
3636 }
3637 ++stats.numSegments;
3638 stats.totalTime += segment.totalTime;
3639 }
3640}
3641
Brian Andersond6927fb2016-07-23 23:37:30 -07003642void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3643 result.appendFormat("Layer frame timestamps:\n");
3644
3645 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3646 const size_t count = currentLayers.size();
3647 for (size_t i=0 ; i<count ; i++) {
3648 currentLayers[i]->dumpFrameEvents(result);
3649 }
3650}
3651
Dan Stozae77c7662016-05-13 11:37:28 -07003652void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3653 result.append("Buffering stats:\n");
3654 result.append(" [Layer name] <Active time> <Two buffer> "
3655 "<Double buffered> <Triple buffered>\n");
3656 Mutex::Autolock lock(mBufferingStatsMutex);
3657 typedef std::tuple<std::string, float, float, float> BufferTuple;
3658 std::map<float, BufferTuple, std::greater<float>> sorted;
3659 for (const auto& statsPair : mBufferingStats) {
3660 const char* name = statsPair.first.c_str();
3661 const BufferingStats& stats = statsPair.second;
3662 if (stats.numSegments == 0) {
3663 continue;
3664 }
3665 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3666 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3667 stats.totalTime;
3668 float doubleBufferRatio = static_cast<float>(
3669 stats.doubleBufferedTime) / stats.totalTime;
3670 float tripleBufferRatio = static_cast<float>(
3671 stats.tripleBufferedTime) / stats.totalTime;
3672 sorted.insert({activeTime, {name, twoBufferRatio,
3673 doubleBufferRatio, tripleBufferRatio}});
3674 }
3675 for (const auto& sortedPair : sorted) {
3676 float activeTime = sortedPair.first;
3677 const BufferTuple& values = sortedPair.second;
3678 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3679 std::get<0>(values).c_str(), activeTime,
3680 std::get<1>(values), std::get<2>(values),
3681 std::get<3>(values));
3682 }
3683 result.append("\n");
3684}
3685
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003686void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3687 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3688
3689 // TODO: print out if wide-color mode is active or not
3690
3691 for (size_t d = 0; d < mDisplays.size(); d++) {
3692 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3693 int32_t hwcId = displayDevice->getHwcDisplayId();
3694 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3695 continue;
3696 }
3697
3698 result.appendFormat("Display %d color modes:\n", hwcId);
3699 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3700 for (auto&& mode : modes) {
3701 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3702 }
3703
3704 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3705 result.appendFormat(" Current color mode: %s (%d)\n",
3706 decodeColorMode(currentMode).c_str(), currentMode);
3707 }
3708 result.append("\n");
3709}
3710
Mathias Agopian74d211a2013-04-22 16:55:35 +02003711void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3712 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003713{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003714 bool colorize = false;
3715 if (index < args.size()
3716 && (args[index] == String16("--color"))) {
3717 colorize = true;
3718 index++;
3719 }
3720
3721 Colorizer colorizer(colorize);
3722
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003723 // figure out if we're stuck somewhere
3724 const nsecs_t now = systemTime();
3725 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3726 const nsecs_t inTransaction(mDebugInTransaction);
3727 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3728 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3729
3730 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003731 * Dump library configuration.
3732 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003733
3734 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003735 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003736 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003737 appendSfConfigString(result);
3738 appendUiConfigString(result);
3739 appendGuiConfigString(result);
3740 result.append("\n");
3741
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003742 result.append("\nWide-Color information:\n");
3743 dumpWideColorInfo(result);
3744
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003745 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003746 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003747 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003748 result.append(SyncFeatures::getInstance().toString());
3749 result.append("\n");
3750
Dan Stoza9e56aa02015-11-02 13:00:03 -08003751 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3752
Andy McFadden41d67d72014-04-25 16:58:34 -07003753 colorizer.bold(result);
3754 result.append("DispSync configuration: ");
3755 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003756 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003757 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003758 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003759 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003760 result.append("\n");
3761
Dan Stozab90cf072015-03-05 11:05:59 -08003762 // Dump static screen stats
3763 result.append("\n");
3764 dumpStaticScreenStats(result);
3765 result.append("\n");
3766
Dan Stozae77c7662016-05-13 11:37:28 -07003767 dumpBufferingStats(result);
3768
Andy McFadden4803b742012-09-24 19:07:20 -07003769 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003770 * Dump the visible layer list
3771 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003772 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003773 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003774 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003775 mCurrentState.traverseInZOrder([&](Layer* layer) {
Kalle Raitaa099a242017-01-11 11:17:29 -08003776 result.append(to_string(layer->getLayerDebugInfo()).c_str());
Robert Carr2047fae2016-11-28 14:09:09 -08003777 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003778
3779 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003780 * Dump Display state
3781 */
3782
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003783 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003784 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003785 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003786 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3787 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003788 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003789 }
3790
3791 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003792 * Dump SurfaceFlinger global state
3793 */
3794
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003795 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003796 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003797 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003798
Mathias Agopian888c8222012-08-04 21:10:38 -07003799 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003800 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003801
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003802 colorizer.bold(result);
3803 result.appendFormat("EGL implementation : %s\n",
3804 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3805 colorizer.reset(result);
3806 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003807 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003808
Mathias Agopian875d8e12013-06-07 15:35:48 -07003809 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003810
Mathias Agopian42977342012-08-05 00:40:46 -07003811 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003812 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3813 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003814 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003815 " last eglSwapBuffers() time: %f us\n"
3816 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003817 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003818 " refresh-rate : %f fps\n"
3819 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003820 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003821 " gpu_to_cpu_unsupported : %d\n"
3822 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003823 mLastSwapBufferTime/1000.0,
3824 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003825 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003826 1e9 / activeConfig->getVsyncPeriod(),
3827 activeConfig->getDpiX(),
3828 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003829 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003830
Mathias Agopian74d211a2013-04-22 16:55:35 +02003831 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003832 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003833
Mathias Agopian74d211a2013-04-22 16:55:35 +02003834 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003835 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003836
3837 /*
3838 * VSYNC state
3839 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003840 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003841 result.append("\n");
3842
3843 /*
3844 * HWC layer minidump
3845 */
3846 for (size_t d = 0; d < mDisplays.size(); d++) {
3847 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3848 int32_t hwcId = displayDevice->getHwcDisplayId();
3849 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3850 continue;
3851 }
3852
3853 result.appendFormat("Display %d HWC layers:\n", hwcId);
3854 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003855 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003856 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003857 });
Dan Stozae22aec72016-08-01 13:20:59 -07003858 result.append("\n");
3859 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003860
3861 /*
3862 * Dump HWComposer state
3863 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003864 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003865 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003866 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003867 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003868 result.appendFormat(" h/w composer %s\n",
3869 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003870 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003871
3872 /*
3873 * Dump gralloc state
3874 */
3875 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3876 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003877
3878 /*
3879 * Dump VrFlinger state if in use.
3880 */
3881 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3882 result.append("VrFlinger state:\n");
3883 result.append(mVrFlinger->Dump().c_str());
3884 result.append("\n");
3885 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003886}
3887
Mathias Agopian13127d82013-03-05 17:47:11 -08003888const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003889SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003890 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003891 wp<IBinder> dpy;
3892 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3893 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3894 dpy = mDisplays.keyAt(i);
3895 break;
3896 }
3897 }
3898 if (dpy == NULL) {
3899 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3900 // Just use the primary display so we have something to return
3901 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3902 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003903 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003904}
3905
Keun young Park63f165f2012-08-31 10:53:36 -07003906bool SurfaceFlinger::startDdmConnection()
3907{
3908 void* libddmconnection_dso =
3909 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3910 if (!libddmconnection_dso) {
3911 return false;
3912 }
3913 void (*DdmConnection_start)(const char* name);
3914 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003915 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003916 if (!DdmConnection_start) {
3917 dlclose(libddmconnection_dso);
3918 return false;
3919 }
3920 (*DdmConnection_start)(getServiceName());
3921 return true;
3922}
3923
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003924status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003925 switch (code) {
3926 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003927 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003929 case CLEAR_ANIMATION_FRAME_STATS:
3930 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003931 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003932 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003933 {
3934 // codes that require permission check
3935 IPCThreadState* ipc = IPCThreadState::self();
3936 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003937 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003938 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003939 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003940 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003941 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003942 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003943 break;
3944 }
Robert Carr1db73f62016-12-21 12:58:51 -08003945 /*
3946 * Calling setTransactionState is safe, because you need to have been
3947 * granted a reference to Client* and Handle* to do anything with it.
3948 *
3949 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3950 */
3951 case SET_TRANSACTION_STATE:
3952 case CREATE_SCOPED_CONNECTION:
3953 {
3954 return OK;
3955 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003956 case CAPTURE_SCREEN:
3957 {
3958 // codes that require permission check
3959 IPCThreadState* ipc = IPCThreadState::self();
3960 const int pid = ipc->getCallingPid();
3961 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003962 if ((uid != AID_GRAPHICS) &&
3963 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003964 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003965 return PERMISSION_DENIED;
3966 }
3967 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003968 }
3969 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003970 return OK;
3971}
3972
3973status_t SurfaceFlinger::onTransact(
3974 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3975{
3976 status_t credentialCheck = CheckTransactCodeCredentials(code);
3977 if (credentialCheck != OK) {
3978 return credentialCheck;
3979 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003980
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003981 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3982 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003983 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003984 IPCThreadState* ipc = IPCThreadState::self();
3985 const int uid = ipc->getCallingUid();
3986 if (CC_UNLIKELY(uid != AID_SYSTEM
3987 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003988 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003989 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003990 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003991 return PERMISSION_DENIED;
3992 }
3993 int n;
3994 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003995 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003996 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003997 return NO_ERROR;
3998 case 1002: // SHOW_UPDATES
3999 n = data.readInt32();
4000 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004001 invalidateHwcGeometry();
4002 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004003 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004004 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004005 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004006 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004007 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004008 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07004009 setTransactionFlags(
4010 eTransactionNeeded|
4011 eDisplayTransactionNeeded|
4012 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004013 return NO_ERROR;
4014 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004015 case 1006:{ // send empty update
4016 signalRefresh();
4017 return NO_ERROR;
4018 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004019 case 1008: // toggle use of hw composer
4020 n = data.readInt32();
4021 mDebugDisableHWC = n ? 1 : 0;
4022 invalidateHwcGeometry();
4023 repaintEverything();
4024 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004025 case 1009: // toggle use of transform hint
4026 n = data.readInt32();
4027 mDebugDisableTransformHint = n ? 1 : 0;
4028 invalidateHwcGeometry();
4029 repaintEverything();
4030 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004031 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004032 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004033 reply->writeInt32(0);
4034 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004035 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004036 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004037 return NO_ERROR;
4038 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004039 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004040 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004041 return NO_ERROR;
4042 }
4043 case 1014: {
4044 // daltonize
4045 n = data.readInt32();
4046 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004047 case 1:
4048 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4049 break;
4050 case 2:
4051 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4052 break;
4053 case 3:
4054 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4055 break;
4056 default:
4057 mDaltonizer.setType(ColorBlindnessType::None);
4058 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004059 }
4060 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004061 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004062 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004063 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004064 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004065 invalidateHwcGeometry();
4066 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004067 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004068 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004069 case 1015: {
4070 // apply a color matrix
4071 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004072 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004073 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004074 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004075 for (size_t j = 0; j < 4; j++) {
4076 mColorMatrix[i][j] = data.readFloat();
4077 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004078 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004079 } else {
4080 mColorMatrix = mat4();
4081 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004082
4083 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4084 // the division by w in the fragment shader
4085 float4 lastRow(transpose(mColorMatrix)[3]);
4086 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4087 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4088 }
4089
Alan Viverette9c5a3332013-09-12 20:04:35 -07004090 invalidateHwcGeometry();
4091 repaintEverything();
4092 return NO_ERROR;
4093 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004094 // This is an experimental interface
4095 // Needs to be shifted to proper binder interface when we productize
4096 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004097 n = data.readInt32();
4098 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004099 return NO_ERROR;
4100 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004101 case 1017: {
4102 n = data.readInt32();
4103 mForceFullDamage = static_cast<bool>(n);
4104 return NO_ERROR;
4105 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004106 case 1018: { // Modify Choreographer's phase offset
4107 n = data.readInt32();
4108 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4109 return NO_ERROR;
4110 }
4111 case 1019: { // Modify SurfaceFlinger's phase offset
4112 n = data.readInt32();
4113 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4114 return NO_ERROR;
4115 }
Irvel468051e2016-06-13 16:44:44 -07004116 case 1020: { // Layer updates interceptor
4117 n = data.readInt32();
4118 if (n) {
4119 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004120 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004121 }
4122 else{
4123 ALOGV("Interceptor disabled");
4124 mInterceptor.disable();
4125 }
4126 return NO_ERROR;
4127 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004128 case 1021: { // Disable HWC virtual displays
4129 n = data.readInt32();
4130 mUseHwcVirtualDisplays = !n;
4131 return NO_ERROR;
4132 }
Romain Guy0147a172017-06-01 13:53:56 -07004133 case 1022: { // Set saturation boost
4134 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4135
4136 invalidateHwcGeometry();
4137 repaintEverything();
4138 return NO_ERROR;
4139 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004140 }
4141 }
4142 return err;
4143}
4144
Mathias Agopian53331da2011-08-22 21:44:41 -07004145void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004146 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004147 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004148}
4149
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004150// Checks that the requested width and height are valid and updates them to the display dimensions
4151// if they are set to 0
4152static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4153 Transform::orientation_flags rotation,
4154 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4155 // get screen geometry
4156 uint32_t displayWidth = displayDevice->getWidth();
4157 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004158
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004159 if (rotation & Transform::ROT_90) {
4160 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004161 }
4162
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004163 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4164 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4165 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4166 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004167 }
4168
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004169 if (*requestedWidth == 0) {
4170 *requestedWidth = displayWidth;
4171 }
4172 if (*requestedHeight == 0) {
4173 *requestedHeight = displayHeight;
4174 }
4175
4176 return NO_ERROR;
4177}
4178
4179// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4180class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004181public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004182 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4183 ~WindowDisconnector() {
4184 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004185 }
4186
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004187private:
4188 ANativeWindow* mWindow;
4189 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004190};
4191
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004192static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4193 uint32_t requestedHeight, bool hasWideColorDisplay,
4194 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4195 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4196 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4197
4198 int err = 0;
4199 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4200 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4201 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4202 err |= native_window_set_usage(window, usage);
4203
4204 if (hasWideColorDisplay) {
4205 err |= native_window_set_buffers_data_space(window,
4206 renderEngineUsesWideColor
4207 ? HAL_DATASPACE_DISPLAY_P3
4208 : HAL_DATASPACE_V0_SRGB);
4209 }
4210
4211 if (err != NO_ERROR) {
4212 return BAD_VALUE;
4213 }
4214
4215 /* TODO: Once we have the sync framework everywhere this can use
4216 * server-side waits on the fence that dequeueBuffer returns.
4217 */
4218 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4219 if (err != NO_ERROR) {
4220 return err;
4221 }
4222
4223 return NO_ERROR;
4224}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004225
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004226status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4227 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004228 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004229 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004230 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004231 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004232
4233 if (CC_UNLIKELY(display == 0))
4234 return BAD_VALUE;
4235
4236 if (CC_UNLIKELY(producer == 0))
4237 return BAD_VALUE;
4238
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004239 // if we have secure windows on this display, never allow the screen capture
4240 // unless the producer interface is local (i.e.: we can take a screenshot for
4241 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004242 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004243
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004244 // Convert to surfaceflinger's internal rotation type.
4245 Transform::orientation_flags rotationFlags;
4246 switch (rotation) {
4247 case ISurfaceComposer::eRotateNone:
4248 rotationFlags = Transform::ROT_0;
4249 break;
4250 case ISurfaceComposer::eRotate90:
4251 rotationFlags = Transform::ROT_90;
4252 break;
4253 case ISurfaceComposer::eRotate180:
4254 rotationFlags = Transform::ROT_180;
4255 break;
4256 case ISurfaceComposer::eRotate270:
4257 rotationFlags = Transform::ROT_270;
4258 break;
4259 default:
4260 rotationFlags = Transform::ROT_0;
4261 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4262 break;
4263 }
4264
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004265 { // Autolock scope
4266 Mutex::Autolock lock(mStateLock);
4267 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4268 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004269 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004270
4271 // create a surface (because we're a producer, and we need to
4272 // dequeue/queue a buffer)
4273 sp<Surface> surface = new Surface(producer, false);
4274
4275 // Put the screenshot Surface into async mode so that
4276 // Layer::headFenceHasSignaled will always return true and we'll latch the
4277 // first buffer regardless of whether or not its acquire fence has
4278 // signaled. This is needed to avoid a race condition in the rotation
4279 // animation. See b/30209608
4280 surface->setAsyncMode(true);
4281
4282 ANativeWindow* window = surface.get();
4283
4284 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4285 if (result != NO_ERROR) {
4286 return result;
4287 }
4288 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4289
4290 ANativeWindowBuffer* buffer = nullptr;
4291 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4292 getRenderEngine().usesWideColor(), &buffer);
4293 if (result != NO_ERROR) {
4294 return result;
4295 }
4296
4297 // This mutex protects syncFd and captureResult for communication of the return values from the
4298 // main thread back to this Binder thread
4299 std::mutex captureMutex;
4300 std::condition_variable captureCondition;
4301 std::unique_lock<std::mutex> captureLock(captureMutex);
4302 int syncFd = -1;
4303 std::optional<status_t> captureResult;
4304
4305 sp<LambdaMessage> message = new LambdaMessage([&]() {
4306 // If there is a refresh pending, bug out early and tell the binder thread to try again
4307 // after the refresh.
4308 if (mRefreshPending) {
4309 ATRACE_NAME("Skipping screenshot for now");
4310 std::unique_lock<std::mutex> captureLock(captureMutex);
4311 captureResult = std::make_optional<status_t>(EAGAIN);
4312 captureCondition.notify_one();
4313 return;
4314 }
4315
4316 status_t result = NO_ERROR;
4317 int fd = -1;
4318 {
4319 Mutex::Autolock _l(mStateLock);
4320 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4321 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4322 minLayerZ, maxLayerZ, useIdentityTransform,
4323 rotationFlags, isLocalScreenshot, &fd);
4324 }
4325
4326 {
4327 std::unique_lock<std::mutex> captureLock(captureMutex);
4328 syncFd = fd;
4329 captureResult = std::make_optional<status_t>(result);
4330 captureCondition.notify_one();
4331 }
4332 });
4333
4334 result = postMessageAsync(message);
4335 if (result == NO_ERROR) {
4336 captureCondition.wait(captureLock, [&]() { return captureResult; });
4337 while (*captureResult == EAGAIN) {
4338 captureResult.reset();
4339 result = postMessageAsync(message);
4340 if (result != NO_ERROR) {
4341 return result;
4342 }
4343 captureCondition.wait(captureLock, [&]() { return captureResult; });
4344 }
4345 result = *captureResult;
4346 }
4347
4348 if (result == NO_ERROR) {
4349 // queueBuffer takes ownership of syncFd
4350 result = window->queueBuffer(window, buffer, syncFd);
4351 }
4352
4353 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004354}
4355
Mathias Agopian180f10d2013-04-10 22:55:41 -07004356
4357void SurfaceFlinger::renderScreenImplLocked(
4358 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004359 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004360 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004361 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004362{
4363 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004364 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004365
4366 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004367 const int32_t hw_w = hw->getWidth();
4368 const int32_t hw_h = hw->getHeight();
4369 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004370 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004371
Dan Stozac1879002014-05-22 15:59:05 -07004372 // if a default or invalid sourceCrop is passed in, set reasonable values
4373 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4374 !sourceCrop.isValid()) {
4375 sourceCrop.setLeftTop(Point(0, 0));
4376 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4377 }
4378
4379 // ensure that sourceCrop is inside screen
4380 if (sourceCrop.left < 0) {
4381 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4382 }
Dan Stozabe31f442014-06-11 11:20:54 -07004383 if (sourceCrop.right > hw_w) {
4384 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004385 }
4386 if (sourceCrop.top < 0) {
4387 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4388 }
Dan Stozabe31f442014-06-11 11:20:54 -07004389 if (sourceCrop.bottom > hw_h) {
4390 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004391 }
4392
Romain Guy88d37dd2017-05-26 17:57:05 -07004393#ifdef USE_HWC2
4394 engine.setWideColor(hw->getWideColorSupport());
4395 engine.setColorMode(hw->getActiveColorMode());
4396#endif
4397
Mathias Agopian180f10d2013-04-10 22:55:41 -07004398 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004399 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004400
4401 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004402 engine.setViewportAndProjection(
4403 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004404 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004405
4406 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004407 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004408
Robert Carr1f0a16a2016-10-24 16:27:39 -07004409 // We loop through the first level of layers without traversing,
4410 // as we need to interpret min/max layer Z in the top level Z space.
4411 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004412 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004413 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004414 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004415 const Layer::State& state(layer->getDrawingState());
4416 if (state.z < minLayerZ || state.z > maxLayerZ) {
4417 continue;
4418 }
Dan Stoza412903f2017-04-27 13:42:17 -07004419 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004420 if (!layer->isVisible()) {
4421 return;
4422 }
4423 if (filtering) layer->setFiltering(true);
4424 layer->draw(hw, useIdentityTransform);
4425 if (filtering) layer->setFiltering(false);
4426 });
4427 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004428
Mathias Agopian931bda12013-08-28 18:11:46 -07004429 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004430}
4431
Dan Stozaabcda352017-06-01 14:37:39 -07004432// A simple RAII class that holds an EGLImage and destroys it either:
4433// a) When the destroy() method is called
4434// b) When the object goes out of scope
4435class ImageHolder {
4436public:
4437 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4438 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004439
Dan Stozaabcda352017-06-01 14:37:39 -07004440 void destroy() {
4441 if (mImage != EGL_NO_IMAGE_KHR) {
4442 eglDestroyImageKHR(mDisplay, mImage);
4443 mImage = EGL_NO_IMAGE_KHR;
4444 }
4445 }
4446
4447private:
4448 const EGLDisplay mDisplay;
4449 EGLImageKHR mImage;
4450};
4451
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004452status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4453 ANativeWindowBuffer* buffer, Rect sourceCrop,
4454 uint32_t reqWidth, uint32_t reqHeight,
4455 int32_t minLayerZ, int32_t maxLayerZ,
4456 bool useIdentityTransform,
4457 Transform::orientation_flags rotation,
4458 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004459 ATRACE_CALL();
4460
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004461 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004462 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004463 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004464 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004465 (state.z < minLayerZ || state.z > maxLayerZ)) {
4466 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004467 }
Dan Stoza412903f2017-04-27 13:42:17 -07004468 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004469 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4470 layer->isSecure());
4471 });
4472 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004473
4474 if (!isLocalScreenshot && secureLayerIsVisible) {
4475 ALOGW("FB is protected: PERMISSION_DENIED");
4476 return PERMISSION_DENIED;
4477 }
4478
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004479 int syncFd = -1;
4480 // create an EGLImage from the buffer so we can later
4481 // turn it into a texture
4482 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4483 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4484 if (image == EGL_NO_IMAGE_KHR) {
4485 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004486 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004487
Dan Stozaabcda352017-06-01 14:37:39 -07004488 // This will automatically destroy the image if we return before calling its destroy method
4489 ImageHolder imageHolder(mEGLDisplay, image);
4490
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004491 // this binds the given EGLImage as a framebuffer for the
4492 // duration of this scope.
4493 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004494 if (imageBond.getStatus() != NO_ERROR) {
4495 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004496 return INVALID_OPERATION;
4497 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004498
Dan Stozaabcda352017-06-01 14:37:39 -07004499 // this will in fact render into our dequeued buffer
4500 // via an FBO, which means we didn't have to create
4501 // an EGLSurface and therefore we're not
4502 // dependent on the context's EGLConfig.
4503 renderScreenImplLocked(
4504 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4505 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004506
Dan Stozaabcda352017-06-01 14:37:39 -07004507 // Attempt to create a sync khr object that can produce a sync point. If that
4508 // isn't available, create a non-dupable sync object in the fallback path and
4509 // wait on it directly.
4510 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4511 if (!DEBUG_SCREENSHOTS) {
4512 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4513 // native fence fd will not be populated until flush() is done.
4514 getRenderEngine().flush();
4515 }
4516
4517 if (sync != EGL_NO_SYNC_KHR) {
4518 // get the sync fd
4519 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4520 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4521 ALOGW("captureScreen: failed to dup sync khr object");
4522 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004523 }
Dan Stozaabcda352017-06-01 14:37:39 -07004524 eglDestroySyncKHR(mEGLDisplay, sync);
4525 } else {
4526 // fallback path
4527 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004528 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004529 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4530 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4531 EGLint eglErr = eglGetError();
4532 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4533 ALOGW("captureScreen: fence wait timed out");
4534 } else {
4535 ALOGW_IF(eglErr != EGL_SUCCESS,
4536 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004537 }
4538 eglDestroySyncKHR(mEGLDisplay, sync);
4539 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004540 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004541 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004542 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004543 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004544
4545 if (DEBUG_SCREENSHOTS) {
4546 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4547 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4548 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4549 hw, minLayerZ, maxLayerZ);
4550 delete [] pixels;
4551 }
4552
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004553 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004554 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004555
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004556 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004557}
4558
Mathias Agopiand5556842013-09-19 17:08:37 -07004559void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004560 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004561 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004562 for (size_t y=0 ; y<h ; y++) {
4563 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4564 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004565 if (p[x] != 0xFF000000) return;
4566 }
4567 }
4568 ALOGE("*** we just took a black screenshot ***\n"
4569 "requested minz=%d, maxz=%d, layerStack=%d",
4570 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004571
Robert Carr2047fae2016-11-28 14:09:09 -08004572 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004573 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004574 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004575 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004576 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004577 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004578 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4579 layer->isVisible() ? '+' : '-',
4580 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004581 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004582 i++;
4583 });
4584 }
4585 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004586 }
4587}
4588
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004589// ---------------------------------------------------------------------------
4590
Dan Stoza412903f2017-04-27 13:42:17 -07004591void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4592 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004593}
4594
Dan Stoza412903f2017-04-27 13:42:17 -07004595void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4596 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004597}
4598
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004599}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004600
4601
4602#if defined(__gl_h_)
4603#error "don't include gl/gl.h in this file"
4604#endif
4605
4606#if defined(__gl2_h_)
4607#error "don't include gl2/gl2.h in this file"
4608#endif