blob: c445758f1b2c45608f71faf2410b26394e51e869 [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) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700633 // This callback is called from the vr flinger dispatch thread. We
634 // need to call signalTransaction(), which requires holding
635 // mStateLock when we're not on the main thread. Acquiring
636 // mStateLock from the vr flinger dispatch thread might trigger a
637 // deadlock in surface flinger (see b/66916578), so post a message
638 // to be handled on the main thread instead.
639 sp<LambdaMessage> message = new LambdaMessage([=]() {
640 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
641 mVrFlingerRequestsDisplay = requestDisplay;
642 signalTransaction();
643 });
644 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800645 };
646 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
647 vrFlingerRequestDisplayCallback);
648 if (!mVrFlinger) {
649 ALOGE("Failed to start vrflinger");
650 }
651 }
652
Jamie Gennisd1700752013-10-14 12:22:52 -0700653 mEventControlThread = new EventControlThread(this);
654 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
655
Mathias Agopian92a979a2012-08-02 18:32:23 -0700656 // initialize our drawing state
657 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700658
Andy McFadden13a082e2012-08-24 10:16:42 -0700659 // set initial conditions (e.g. unblank default device)
660 initializeDisplays();
661
Dan Stoza4e637772016-07-28 13:31:51 -0700662 mRenderEngine->primeCache();
663
Wei Wangf9b05ee2017-07-19 20:59:39 -0700664 // Inform native graphics APIs whether the present timestamp is supported:
665 if (getHwComposer().hasCapability(
666 HWC2::Capability::PresentFenceIsNotReliable)) {
667 mStartPropertySetThread = new StartPropertySetThread(false);
668 } else {
669 mStartPropertySetThread = new StartPropertySetThread(true);
670 }
671
672 if (mStartPropertySetThread->Start() != NO_ERROR) {
673 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800674 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800675
Dan Stoza9e56aa02015-11-02 13:00:03 -0800676 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700677}
678
Romain Guy11d63f42017-07-20 12:47:14 -0700679void SurfaceFlinger::readPersistentProperties() {
680 char value[PROPERTY_VALUE_MAX];
681
682 property_get("persist.sys.sf.color_saturation", value, "1.0");
683 mSaturation = atof(value);
684 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100685
686 property_get("persist.sys.sf.native_mode", value, "0");
687 mForceNativeColorMode = atoi(value) == 1;
688 if (mForceNativeColorMode) {
689 ALOGV("Forcing native color mode");
690 }
Romain Guy11d63f42017-07-20 12:47:14 -0700691}
692
Mathias Agopiana67e4182012-06-19 17:26:12 -0700693void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800694 // Start boot animation service by setting a property mailbox
695 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700696 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800697 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 if (mStartPropertySetThread->join() != NO_ERROR) {
699 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800700 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700701}
702
Mathias Agopian875d8e12013-06-07 15:35:48 -0700703size_t SurfaceFlinger::getMaxTextureSize() const {
704 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700705}
706
Mathias Agopian875d8e12013-06-07 15:35:48 -0700707size_t SurfaceFlinger::getMaxViewportDims() const {
708 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700709}
710
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800711// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800712
Jamie Gennis582270d2011-08-17 18:19:00 -0700713bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800714 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800715 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800716 return authenticateSurfaceTextureLocked(bufferProducer);
717}
718
719bool SurfaceFlinger::authenticateSurfaceTextureLocked(
720 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800721 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700722 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800723}
724
Brian Anderson6b376712017-04-04 10:51:39 -0700725status_t SurfaceFlinger::getSupportedFrameTimestamps(
726 std::vector<FrameEvent>* outSupported) const {
727 *outSupported = {
728 FrameEvent::REQUESTED_PRESENT,
729 FrameEvent::ACQUIRE,
730 FrameEvent::LATCH,
731 FrameEvent::FIRST_REFRESH_START,
732 FrameEvent::LAST_REFRESH_START,
733 FrameEvent::GPU_COMPOSITION_DONE,
734 FrameEvent::DEQUEUE_READY,
735 FrameEvent::RELEASE,
736 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700737 ConditionalLock _l(mStateLock,
738 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700739 if (!getHwComposer().hasCapability(
740 HWC2::Capability::PresentFenceIsNotReliable)) {
741 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
742 }
743 return NO_ERROR;
744}
745
Dan Stoza7f7da322014-05-02 15:26:25 -0700746status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
747 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700748 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700749 return BAD_VALUE;
750 }
751
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500752 if (!display.get())
753 return NAME_NOT_FOUND;
754
Jesse Hall692c7232012-11-08 15:41:56 -0800755 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700756 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800757 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700758 type = i;
759 break;
760 }
761 }
762
763 if (type < 0) {
764 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700765 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700766
Mathias Agopian8b736f12012-08-13 17:54:26 -0700767 // TODO: Not sure if display density should handled by SF any longer
768 class Density {
769 static int getDensityFromProperty(char const* propName) {
770 char property[PROPERTY_VALUE_MAX];
771 int density = 0;
772 if (property_get(propName, property, NULL) > 0) {
773 density = atoi(property);
774 }
775 return density;
776 }
777 public:
778 static int getEmuDensity() {
779 return getDensityFromProperty("qemu.sf.lcd_density"); }
780 static int getBuildDensity() {
781 return getDensityFromProperty("ro.sf.lcd_density"); }
782 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700783
Dan Stoza7f7da322014-05-02 15:26:25 -0700784 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700785
Steven Thomas6d8110b2017-08-31 18:24:21 -0700786 ConditionalLock _l(mStateLock,
787 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800788 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700789 DisplayInfo info = DisplayInfo();
790
Dan Stoza9e56aa02015-11-02 13:00:03 -0800791 float xdpi = hwConfig->getDpiX();
792 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700793
794 if (type == DisplayDevice::DISPLAY_PRIMARY) {
795 // The density of the device is provided by a build property
796 float density = Density::getBuildDensity() / 160.0f;
797 if (density == 0) {
798 // the build doesn't provide a density -- this is wrong!
799 // use xdpi instead
800 ALOGE("ro.sf.lcd_density must be defined as a build property");
801 density = xdpi / 160.0f;
802 }
803 if (Density::getEmuDensity()) {
804 // if "qemu.sf.lcd_density" is specified, it overrides everything
805 xdpi = ydpi = density = Density::getEmuDensity();
806 density /= 160.0f;
807 }
808 info.density = density;
809
810 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700811 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000812 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 } else {
814 // TODO: where should this value come from?
815 static const int TV_DENSITY = 213;
816 info.density = TV_DENSITY / 160.0f;
817 info.orientation = 0;
818 }
819
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820 info.w = hwConfig->getWidth();
821 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 info.xdpi = xdpi;
823 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800824 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900825 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826
Andy McFadden91b2ca82014-06-13 14:04:23 -0700827 // This is how far in advance a buffer must be queued for
828 // presentation at a given time. If you want a buffer to appear
829 // on the screen at time N, you must submit the buffer before
830 // (N - presentationDeadline).
831 //
832 // Normally it's one full refresh period (to give SF a chance to
833 // latch the buffer), but this can be reduced by configuring a
834 // DispSync offset. Any additional delays introduced by the hardware
835 // composer or panel must be accounted for here.
836 //
837 // We add an additional 1ms to allow for processing time and
838 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800839 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800840 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700841
842 // All non-virtual displays are currently considered secure.
843 info.secure = true;
844
Michael Wright28f24d02016-07-12 13:30:53 -0700845 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846 }
847
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 return NO_ERROR;
849}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700850
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800851status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700852 DisplayStatInfo* stats) {
853 if (stats == NULL) {
854 return BAD_VALUE;
855 }
856
857 // FIXME for now we always return stats for the primary display
858 memset(stats, 0, sizeof(*stats));
859 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
860 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
861 return NO_ERROR;
862}
863
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700864int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800865 if (display == NULL) {
866 ALOGE("%s : display is NULL", __func__);
867 return BAD_VALUE;
868 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700869
870 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700871 if (device != NULL) {
872 return device->getActiveConfig();
873 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700874
Dan Stoza24a42e92015-03-09 10:04:11 -0700875 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700876}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700877
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700878void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
879 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
880 this);
881 int32_t type = hw->getDisplayType();
882 int currentMode = hw->getActiveConfig();
883
884 if (mode == currentMode) {
885 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
886 return;
887 }
888
889 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
890 ALOGW("Trying to set config for virtual display");
891 return;
892 }
893
894 hw->setActiveConfig(mode);
895 getHwComposer().setActiveConfig(type, mode);
896}
897
898status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
899 class MessageSetActiveConfig: public MessageBase {
900 SurfaceFlinger& mFlinger;
901 sp<IBinder> mDisplay;
902 int mMode;
903 public:
904 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
905 int mode) :
906 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
907 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700908 Vector<DisplayInfo> configs;
909 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700910 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700911 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700912 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700913 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700914 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700915 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
916 if (hw == NULL) {
917 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700918 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700919 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
920 ALOGW("Attempt to set active config = %d for virtual display",
921 mMode);
922 } else {
923 mFlinger.setActiveConfigInternal(hw, mMode);
924 }
925 return true;
926 }
927 };
928 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
929 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700930 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700931}
Michael Wright28f24d02016-07-12 13:30:53 -0700932status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
933 Vector<android_color_mode_t>* outColorModes) {
934 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
935 return BAD_VALUE;
936 }
937
938 if (!display.get()) {
939 return NAME_NOT_FOUND;
940 }
941
942 int32_t type = NAME_NOT_FOUND;
943 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
944 if (display == mBuiltinDisplays[i]) {
945 type = i;
946 break;
947 }
948 }
949
950 if (type < 0) {
951 return type;
952 }
953
Steven Thomas6d8110b2017-08-31 18:24:21 -0700954 std::vector<android_color_mode_t> modes;
955 {
956 ConditionalLock _l(mStateLock,
957 std::this_thread::get_id() != mMainThreadId);
958 modes = getHwComposer().getColorModes(type);
959 }
Michael Wright28f24d02016-07-12 13:30:53 -0700960 outColorModes->clear();
961 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
962
963 return NO_ERROR;
964}
965
966android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700967 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700968 if (device != nullptr) {
969 return device->getActiveColorMode();
970 }
971 return static_cast<android_color_mode_t>(BAD_VALUE);
972}
973
974void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
975 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700976 int32_t type = hw->getDisplayType();
977 android_color_mode_t currentMode = hw->getActiveColorMode();
978
979 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700980 return;
981 }
982
983 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
984 ALOGW("Trying to set config for virtual display");
985 return;
986 }
987
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600988 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
989 hw->getDisplayType());
990
Michael Wright28f24d02016-07-12 13:30:53 -0700991 hw->setActiveColorMode(mode);
992 getHwComposer().setActiveColorMode(type, mode);
993}
994
995
996status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
997 android_color_mode_t colorMode) {
998 class MessageSetActiveColorMode: public MessageBase {
999 SurfaceFlinger& mFlinger;
1000 sp<IBinder> mDisplay;
1001 android_color_mode_t mMode;
1002 public:
1003 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1004 android_color_mode_t mode) :
1005 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1006 virtual bool handler() {
1007 Vector<android_color_mode_t> modes;
1008 mFlinger.getDisplayColorModes(mDisplay, &modes);
1009 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1010 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001011 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1012 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001013 return true;
1014 }
1015 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1016 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001017 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1018 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001019 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001020 ALOGW("Attempt to set active color mode %s %d for virtual display",
1021 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001022 } else {
1023 mFlinger.setActiveColorModeInternal(hw, mMode);
1024 }
1025 return true;
1026 }
1027 };
1028 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1029 postMessageSync(msg);
1030 return NO_ERROR;
1031}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001032
Svetoslavd85084b2014-03-20 10:28:31 -07001033status_t SurfaceFlinger::clearAnimationFrameStats() {
1034 Mutex::Autolock _l(mStateLock);
1035 mAnimFrameTracker.clearStats();
1036 return NO_ERROR;
1037}
1038
1039status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1040 Mutex::Autolock _l(mStateLock);
1041 mAnimFrameTracker.getStats(outStats);
1042 return NO_ERROR;
1043}
1044
Dan Stozac4f471e2016-03-24 09:31:08 -07001045status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1046 HdrCapabilities* outCapabilities) const {
1047 Mutex::Autolock _l(mStateLock);
1048
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001049 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001050 if (displayDevice == nullptr) {
1051 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1052 return BAD_VALUE;
1053 }
1054
1055 std::unique_ptr<HdrCapabilities> capabilities =
1056 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1057 if (capabilities) {
1058 std::swap(*outCapabilities, *capabilities);
1059 } else {
1060 return BAD_VALUE;
1061 }
1062
1063 return NO_ERROR;
1064}
1065
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001066status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1067 if (enable == mInjectVSyncs) {
1068 return NO_ERROR;
1069 }
1070
1071 if (enable) {
1072 mInjectVSyncs = enable;
1073 ALOGV("VSync Injections enabled");
1074 if (mVSyncInjector.get() == nullptr) {
1075 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001076 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001077 }
1078 mEventQueue.setEventThread(mInjectorEventThread);
1079 } else {
1080 mInjectVSyncs = enable;
1081 ALOGV("VSync Injections disabled");
1082 mEventQueue.setEventThread(mSFEventThread);
1083 mVSyncInjector.clear();
1084 }
1085 return NO_ERROR;
1086}
1087
1088status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1089 if (!mInjectVSyncs) {
1090 ALOGE("VSync Injections not enabled");
1091 return BAD_VALUE;
1092 }
1093 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1094 ALOGV("Injecting VSync inside SurfaceFlinger");
1095 mVSyncInjector->onInjectSyncEvent(when);
1096 }
1097 return NO_ERROR;
1098}
1099
Kalle Raitaa099a242017-01-11 11:17:29 -08001100status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1101 IPCThreadState* ipc = IPCThreadState::self();
1102 const int pid = ipc->getCallingPid();
1103 const int uid = ipc->getCallingUid();
1104 if ((uid != AID_SHELL) &&
1105 !PermissionCache::checkPermission(sDump, pid, uid)) {
1106 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1107 return PERMISSION_DENIED;
1108 }
1109
1110 // Try to acquire a lock for 1s, fail gracefully
1111 const status_t err = mStateLock.timedLock(s2ns(1));
1112 const bool locked = (err == NO_ERROR);
1113 if (!locked) {
1114 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1115 return TIMED_OUT;
1116 }
1117
1118 outLayers->clear();
1119 mCurrentState.traverseInZOrder([&](Layer* layer) {
1120 outLayers->push_back(layer->getLayerDebugInfo());
1121 });
1122
1123 mStateLock.unlock();
1124 return NO_ERROR;
1125}
1126
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001127// ----------------------------------------------------------------------------
1128
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001129sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1130 ISurfaceComposer::VsyncSource vsyncSource) {
1131 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1132 return mSFEventThread->createEventConnection();
1133 } else {
1134 return mEventThread->createEventConnection();
1135 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001136}
1137
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001138// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001139
1140void SurfaceFlinger::waitForEvent() {
1141 mEventQueue.waitMessage();
1142}
1143
1144void SurfaceFlinger::signalTransaction() {
1145 mEventQueue.invalidate();
1146}
1147
1148void SurfaceFlinger::signalLayerUpdate() {
1149 mEventQueue.invalidate();
1150}
1151
1152void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001153 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001154 mEventQueue.refresh();
1155}
1156
1157status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001158 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001159 return mEventQueue.postMessage(msg, reltime);
1160}
1161
1162status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001163 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001164 status_t res = mEventQueue.postMessage(msg, reltime);
1165 if (res == NO_ERROR) {
1166 msg->wait();
1167 }
1168 return res;
1169}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001170
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001171void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001172 do {
1173 waitForEvent();
1174 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001175}
1176
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001177void SurfaceFlinger::enableHardwareVsync() {
1178 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001179 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001180 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001181 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1182 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001183 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001184 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001185}
1186
Jesse Hall948fe0c2013-10-14 12:56:09 -07001187void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001188 Mutex::Autolock _l(mHWVsyncLock);
1189
Jesse Hall948fe0c2013-10-14 12:56:09 -07001190 if (makeAvailable) {
1191 mHWVsyncAvailable = true;
1192 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001193 // Hardware vsync is not currently available, so abort the resync
1194 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001195 return;
1196 }
1197
Dan Stoza9e56aa02015-11-02 13:00:03 -08001198 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1199 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001200
1201 mPrimaryDispSync.reset();
1202 mPrimaryDispSync.setPeriod(period);
1203
1204 if (!mPrimaryHWVsyncEnabled) {
1205 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001206 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1207 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001208 mPrimaryHWVsyncEnabled = true;
1209 }
1210}
1211
Jesse Hall948fe0c2013-10-14 12:56:09 -07001212void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001213 Mutex::Autolock _l(mHWVsyncLock);
1214 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001215 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1216 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217 mPrimaryDispSync.endResync();
1218 mPrimaryHWVsyncEnabled = false;
1219 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001220 if (makeUnavailable) {
1221 mHWVsyncAvailable = false;
1222 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223}
1224
Tim Murray4a4e4a22016-04-19 16:29:23 +00001225void SurfaceFlinger::resyncWithRateLimit() {
1226 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001227
1228 // No explicit locking is needed here since EventThread holds a lock while calling this method
1229 static nsecs_t sLastResyncAttempted = 0;
1230 const nsecs_t now = systemTime();
1231 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001232 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001233 }
Dan Stoza57164302017-05-08 14:03:54 -07001234 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001235}
1236
Steven Thomasb02664d2017-07-26 18:48:28 -07001237void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1238 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001239 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001240 // Ignore any vsyncs from a previous hardware composer.
1241 if (sequenceId != mComposerSequenceId) {
1242 return;
1243 }
1244
1245 int32_t type;
1246 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001247 return;
1248 }
1249
Jamie Gennisd1700752013-10-14 12:22:52 -07001250 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251
Jamie Gennisd1700752013-10-14 12:22:52 -07001252 { // Scope for the lock
1253 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001254 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001255 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001257 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001258
1259 if (needsHwVsync) {
1260 enableHardwareVsync();
1261 } else {
1262 disableHardwareVsync(false);
1263 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001264}
1265
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001266void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001267 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001268 *compositorTiming = mCompositorTiming;
1269}
1270
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001271void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001272 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001273 wp<IBinder> token = mBuiltinDisplays[type];
1274
1275 // All non-virtual displays are currently considered secure.
1276 const bool isSecure = true;
1277
1278 sp<IGraphicBufferProducer> producer;
1279 sp<IGraphicBufferConsumer> consumer;
1280 BufferQueue::createBufferQueue(&producer, &consumer);
1281
1282 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1283
1284 bool hasWideColorModes = false;
1285 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1286 for (android_color_mode_t colorMode : modes) {
1287 switch (colorMode) {
1288 case HAL_COLOR_MODE_DISPLAY_P3:
1289 case HAL_COLOR_MODE_ADOBE_RGB:
1290 case HAL_COLOR_MODE_DCI_P3:
1291 hasWideColorModes = true;
1292 break;
1293 default:
1294 break;
1295 }
1296 }
Romain Guy54f154a2017-10-24 21:40:32 +01001297 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001298 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1299 token, fbs, producer, mRenderEngine->getEGLConfig(),
Romain Guy54f154a2017-10-24 21:40:32 +01001300 useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001301 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001302 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001303 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001304 defaultColorMode = HAL_COLOR_MODE_SRGB;
1305 }
1306 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001307 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001308
1309 // Add the primary display token to mDrawingState so we don't try to
1310 // recreate the DisplayDevice for the primary display.
1311 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1312
1313 // make the GLContext current so that we can create textures when creating
1314 // Layers (which may happens before we render something)
1315 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001316}
1317
Steven Thomasb02664d2017-07-26 18:48:28 -07001318void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1319 hwc2_display_t display, HWC2::Connection connection,
1320 bool primaryDisplay) {
1321 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1322 sequenceId, display,
1323 connection == HWC2::Connection::Connected ?
1324 "connected" : "disconnected",
1325 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001326
Steven Thomasb02664d2017-07-26 18:48:28 -07001327 // Only lock if we're not on the main thread. This function is normally
1328 // called on a hwbinder thread, but for the primary display it's called on
1329 // the main thread with the state lock already held, so don't attempt to
1330 // acquire it here.
1331 ConditionalLock lock(mStateLock,
1332 std::this_thread::get_id() != mMainThreadId);
1333
1334 if (primaryDisplay) {
1335 mHwc->onHotplug(display, connection);
1336 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1337 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001338 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001339 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001340 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001341 if (sequenceId != mComposerSequenceId) {
1342 return;
1343 }
1344 if (mHwc->isUsingVrComposer()) {
1345 ALOGE("External displays are not supported by the vr hardware composer.");
1346 return;
1347 }
1348 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001349 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001350 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001351 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001352 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001353 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1354 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001355 }
1356 setTransactionFlags(eDisplayTransactionNeeded);
1357
Andy McFadden9e9689c2012-10-10 18:17:51 -07001358 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001359 }
Mathias Agopian86303202012-07-24 22:46:10 -07001360}
1361
Steven Thomasb02664d2017-07-26 18:48:28 -07001362void SurfaceFlinger::onRefreshReceived(int sequenceId,
1363 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001364 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001365 if (sequenceId != mComposerSequenceId) {
1366 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001367 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001368 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001369}
1370
Dan Stoza9e56aa02015-11-02 13:00:03 -08001371void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001372 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001374 getHwComposer().setVsyncEnabled(disp,
1375 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001376}
1377
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001378// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001379void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001380 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001381 // Clear the drawing state so that the logic inside of
1382 // handleTransactionLocked will fire. It will determine the delta between
1383 // mCurrentState and mDrawingState and re-apply all changes when we make the
1384 // transition.
1385 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387 mDisplays.clear();
1388}
1389
Steven Thomas050b2c82017-03-06 11:45:16 -08001390void SurfaceFlinger::updateVrFlinger() {
1391 if (!mVrFlinger)
1392 return;
1393 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1394 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001395 return;
1396 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001397
Steven Thomasb02664d2017-07-26 18:48:28 -07001398 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1399 ALOGE("Vr flinger is only supported for remote hardware composer"
1400 " service connections. Ignoring request to transition to vr"
1401 " flinger.");
1402 mVrFlingerRequestsDisplay = false;
1403 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001404 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001405
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 int currentDisplayPowerMode = getDisplayDeviceLocked(
1409 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001412 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001414
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 resetDisplayState();
1416 mHwc.reset(); // Delete the current instance before creating the new one
1417 mHwc.reset(new HWComposer(
1418 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1419 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1422 "Switched to non-remote hardware composer");
1423
1424 if (vrFlingerRequestsDisplay) {
1425 mVrFlinger->GrantDisplayOwnership();
1426 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001427 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001428 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429
1430 mVisibleRegionsDirty = true;
1431 invalidateHwcGeometry();
1432
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001433 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1435 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1436 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001437
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 // Reset the timing values to account for the period of the swapped in HWC
1439 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1440 const nsecs_t period = activeConfig->getVsyncPeriod();
1441 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001442
Steven Thomasb02664d2017-07-26 18:48:28 -07001443 // Use phase of 0 since phase is not known.
1444 // Use latency of 0, which will snap to the ideal latency.
1445 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001446
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001447 android_atomic_or(1, &mRepaintEverything);
1448 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001449}
1450
Mathias Agopian4fec8732012-06-29 14:12:52 -07001451void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001452 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001453 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001454 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001455 bool frameMissed = !mHadClientComposition &&
1456 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001457 (mPreviousPresentFence->getSignalTime() ==
1458 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001459 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001460 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001461 signalLayerUpdate();
1462 break;
1463 }
1464
Steven Thomas050b2c82017-03-06 11:45:16 -08001465 // Now that we're going to make it to the handleMessageTransaction()
1466 // call below it's safe to call updateVrFlinger(), which will
1467 // potentially trigger a display handoff.
1468 updateVrFlinger();
1469
Dan Stoza6b9454d2014-11-07 16:00:59 -08001470 bool refreshNeeded = handleMessageTransaction();
1471 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001472 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001473 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001474 // Signal a refresh if a transaction modified the window state,
1475 // a new buffer was latched, or if HWC has requested a full
1476 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001477 signalRefresh();
1478 }
1479 break;
1480 }
1481 case MessageQueue::REFRESH: {
1482 handleMessageRefresh();
1483 break;
1484 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001485 }
1486}
1487
Dan Stoza6b9454d2014-11-07 16:00:59 -08001488bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001489 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001490 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001491 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001492 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001493 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001494 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001495}
1496
Dan Stoza6b9454d2014-11-07 16:00:59 -08001497bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001498 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001499 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001500}
1501
1502void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001503 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001504
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001505 mRefreshPending = false;
1506
Pablo Ceballos40845df2016-01-25 17:41:15 -08001507 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001508
Brian Andersond6927fb2016-07-23 23:37:30 -07001509 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001510 rebuildLayerStacks();
1511 setUpHWComposer();
1512 doDebugFlashRegions();
1513 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001514 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001515
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001516 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001517
1518 mHadClientComposition = false;
1519 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1520 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1521 mHadClientComposition = mHadClientComposition ||
1522 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1523 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001524
Dan Stoza9e56aa02015-11-02 13:00:03 -08001525 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001526}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001527
Mathias Agopiancd60f992012-08-16 16:28:27 -07001528void SurfaceFlinger::doDebugFlashRegions()
1529{
1530 // is debugging enabled
1531 if (CC_LIKELY(!mDebugRegion))
1532 return;
1533
1534 const bool repaintEverything = mRepaintEverything;
1535 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1536 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001537 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001538 // transform the dirty region into this screen's coordinate space
1539 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1540 if (!dirtyRegion.isEmpty()) {
1541 // redraw the whole screen
1542 doComposeSurfaces(hw, Region(hw->bounds()));
1543
1544 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001546 RenderEngine& engine(getRenderEngine());
1547 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1548
Mathias Agopianda27af92012-09-13 18:17:13 -07001549 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001550 }
1551 }
1552 }
1553
1554 postFramebuffer();
1555
1556 if (mDebugRegion > 1) {
1557 usleep(mDebugRegion * 1000);
1558 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001559
Dan Stoza9e56aa02015-11-02 13:00:03 -08001560 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001561 auto& displayDevice = mDisplays[displayId];
1562 if (!displayDevice->isDisplayOn()) {
1563 continue;
1564 }
1565
1566 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001567 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1568 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001569 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570}
1571
Brian Andersond6927fb2016-07-23 23:37:30 -07001572void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001573{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001574 ATRACE_CALL();
1575 ALOGV("preComposition");
1576
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001578 mDrawingState.traverseInZOrder([&](Layer* layer) {
1579 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001580 needExtraInvalidate = true;
1581 }
Robert Carr2047fae2016-11-28 14:09:09 -08001582 });
1583
Mathias Agopiancd60f992012-08-16 16:28:27 -07001584 if (needExtraInvalidate) {
1585 signalLayerUpdate();
1586 }
1587}
1588
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001589void SurfaceFlinger::updateCompositorTiming(
1590 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1591 std::shared_ptr<FenceTime>& presentFenceTime) {
1592 // Update queue of past composite+present times and determine the
1593 // most recently known composite to present latency.
1594 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1595 nsecs_t compositeToPresentLatency = -1;
1596 while (!mCompositePresentTimes.empty()) {
1597 CompositePresentTime& cpt = mCompositePresentTimes.front();
1598 // Cached values should have been updated before calling this method,
1599 // which helps avoid duplicate syscalls.
1600 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1601 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1602 break;
1603 }
1604 compositeToPresentLatency = displayTime - cpt.composite;
1605 mCompositePresentTimes.pop();
1606 }
1607
1608 // Don't let mCompositePresentTimes grow unbounded, just in case.
1609 while (mCompositePresentTimes.size() > 16) {
1610 mCompositePresentTimes.pop();
1611 }
1612
Brian Andersond0010582017-03-07 13:20:31 -08001613 setCompositorTimingSnapped(
1614 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1615}
1616
1617void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1618 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001619 // Integer division and modulo round toward 0 not -inf, so we need to
1620 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001621 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001622 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1623 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1624
Brian Andersond0010582017-03-07 13:20:31 -08001625 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1626 if (idealLatency <= 0) {
1627 idealLatency = vsyncInterval;
1628 }
1629
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001630 // Snap the latency to a value that removes scheduling jitter from the
1631 // composition and present times, which often have >1ms of jitter.
1632 // Reducing jitter is important if an app attempts to extrapolate
1633 // something (such as user input) to an accurate diasplay time.
1634 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1635 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001636 nsecs_t bias = vsyncInterval / 2;
1637 int64_t extraVsyncs =
1638 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1639 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1640 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001641
Brian Andersond0010582017-03-07 13:20:31 -08001642 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001643 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1644 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001645 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001646}
1647
1648void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001649{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001650 ATRACE_CALL();
1651 ALOGV("postComposition");
1652
Brian Anderson3546a3f2016-07-14 11:51:14 -07001653 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001654 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001655 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001656 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001657 }
1658
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001659 // |mStateLock| not needed as we are on the main thread
1660 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001661
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001662 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001663 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1664 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1665 glCompositionDoneFenceTime =
1666 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1667 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1668 } else {
1669 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1670 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001671
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001672 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001673 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1674 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1675 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001676
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001677 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1678 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1679
1680 // We use the refreshStartTime which might be sampled a little later than
1681 // when we started doing work for this frame, but that should be okay
1682 // since updateCompositorTiming has snapping logic.
1683 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001684 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001685 CompositorTiming compositorTiming;
1686 {
1687 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1688 compositorTiming = mCompositorTiming;
1689 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001690
Robert Carr2047fae2016-11-28 14:09:09 -08001691 mDrawingState.traverseInZOrder([&](Layer* layer) {
1692 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001693 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001694 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001695 recordBufferingStats(layer->getName().string(),
1696 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001697 }
Robert Carr2047fae2016-11-28 14:09:09 -08001698 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001699
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001700 if (presentFenceTime->isValid()) {
1701 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001702 enableHardwareVsync();
1703 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001704 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001705 }
1706 }
1707
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001708 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001709 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001710 enableHardwareVsync();
1711 }
1712 }
1713
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001714 if (mAnimCompositionPending) {
1715 mAnimCompositionPending = false;
1716
Brian Anderson4e606e32017-03-16 15:34:57 -07001717 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001718 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001719 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001720 } else {
1721 // The HWC doesn't support present fences, so use the refresh
1722 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001723 nsecs_t presentTime =
1724 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001725 mAnimFrameTracker.setActualPresentTime(presentTime);
1726 }
1727 mAnimFrameTracker.advanceFrame();
1728 }
Dan Stozab90cf072015-03-05 11:05:59 -08001729
1730 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1731 return;
1732 }
1733
1734 nsecs_t currentTime = systemTime();
1735 if (mHasPoweredOff) {
1736 mHasPoweredOff = false;
1737 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001738 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001739 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001740 if (numPeriods < NUM_BUCKETS - 1) {
1741 mFrameBuckets[numPeriods] += elapsedTime;
1742 } else {
1743 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1744 }
1745 mTotalTime += elapsedTime;
1746 }
1747 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001748}
1749
1750void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001751 ATRACE_CALL();
1752 ALOGV("rebuildLayerStacks");
1753
Mathias Agopiancd60f992012-08-16 16:28:27 -07001754 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001755 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1756 ATRACE_CALL();
1757 mVisibleRegionsDirty = false;
1758 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001759
Jeff Sharkey76488112017-02-27 14:15:18 -07001760 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1761 Region opaqueRegion;
1762 Region dirtyRegion;
1763 Vector<sp<Layer>> layersSortedByZ;
1764 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1765 const Transform& tr(displayDevice->getTransform());
1766 const Rect bounds(displayDevice->getBounds());
1767 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001768 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001769
Jeff Sharkey76488112017-02-27 14:15:18 -07001770 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001771 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1772 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001773 Region drawRegion(tr.transform(
1774 layer->visibleNonTransparentRegion));
1775 drawRegion.andSelf(bounds);
1776 if (!drawRegion.isEmpty()) {
1777 layersSortedByZ.add(layer);
1778 } else {
1779 // Clear out the HWC layer if this layer was
1780 // previously visible, but no longer is
Steven Thomasb02664d2017-07-26 18:48:28 -07001781 layer->destroyHwcLayer(
1782 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001783 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001784 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001785 // WM changes displayDevice->layerStack upon sleep/awake.
1786 // Here we make sure we delete the HWC layers even if
1787 // WM changed their layer stack.
Steven Thomasb02664d2017-07-26 18:48:28 -07001788 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001789 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001790 });
1791 }
1792 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1793 displayDevice->undefinedRegion.set(bounds);
1794 displayDevice->undefinedRegion.subtractSelf(
1795 tr.transform(opaqueRegion));
1796 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001797 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001798 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001799}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001800
Romain Guy0147a172017-06-01 13:53:56 -07001801mat4 SurfaceFlinger::computeSaturationMatrix() const {
1802 if (mSaturation == 1.0f) {
1803 return mat4();
1804 }
1805
1806 // Rec.709 luma coefficients
1807 float3 luminance{0.213f, 0.715f, 0.072f};
1808 luminance *= 1.0f - mSaturation;
1809 return mat4(
1810 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1811 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1812 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1813 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1814 );
1815}
1816
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001817// pickColorMode translates a given dataspace into the best available color mode.
1818// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001819android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001820 if (mForceNativeColorMode) {
1821 return HAL_COLOR_MODE_NATIVE;
1822 }
1823
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001824 switch (dataSpace) {
1825 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1826 // system expects.
1827 case HAL_DATASPACE_UNKNOWN:
1828 case HAL_DATASPACE_SRGB:
1829 case HAL_DATASPACE_V0_SRGB:
1830 return HAL_COLOR_MODE_SRGB;
1831 break;
1832
1833 case HAL_DATASPACE_DISPLAY_P3:
1834 return HAL_COLOR_MODE_DISPLAY_P3;
1835 break;
1836
1837 default:
1838 // TODO (courtneygo): Do we want to assert an error here?
1839 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1840 dataSpace);
1841 return HAL_COLOR_MODE_SRGB;
1842 break;
1843 }
1844}
1845
Romain Guy0147a172017-06-01 13:53:56 -07001846android_dataspace SurfaceFlinger::bestTargetDataSpace(
1847 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001848 // Only support sRGB and Display-P3 right now.
1849 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1850 return HAL_DATASPACE_DISPLAY_P3;
1851 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001852 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1853 return HAL_DATASPACE_DISPLAY_P3;
1854 }
1855 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1856 return HAL_DATASPACE_DISPLAY_P3;
1857 }
1858
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001859 return HAL_DATASPACE_V0_SRGB;
1860}
1861
Mathias Agopiancd60f992012-08-16 16:28:27 -07001862void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001863 ATRACE_CALL();
1864 ALOGV("setUpHWComposer");
1865
Jesse Hall028dc8f2013-08-20 16:35:32 -07001866 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001867 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1868 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1869 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1870
1871 // If nothing has changed (!dirty), don't recompose.
1872 // If something changed, but we don't currently have any visible layers,
1873 // and didn't when we last did a composition, then skip it this time.
1874 // The second rule does two things:
1875 // - When all layers are removed from a display, we'll emit one black
1876 // frame, then nothing more until we get new layers.
1877 // - When a display is created with a private layer stack, we won't
1878 // emit any black frames until a layer is added to the layer stack.
1879 bool mustRecompose = dirty && !(empty && wasEmpty);
1880
1881 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1882 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1883 mustRecompose ? "doing" : "skipping",
1884 dirty ? "+" : "-",
1885 empty ? "+" : "-",
1886 wasEmpty ? "+" : "-");
1887
Dan Stoza71433162014-02-04 16:22:36 -08001888 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001889
1890 if (mustRecompose) {
1891 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1892 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001893 }
1894
Dan Stoza9e56aa02015-11-02 13:00:03 -08001895 // build the h/w work list
1896 if (CC_UNLIKELY(mGeometryInvalid)) {
1897 mGeometryInvalid = false;
1898 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1899 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1900 const auto hwcId = displayDevice->getHwcDisplayId();
1901 if (hwcId >= 0) {
1902 const Vector<sp<Layer>>& currentLayers(
1903 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001904 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001905 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001906 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001907 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001908 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001909 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001910 }
1911 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001912
Robert Carrae060832016-11-28 10:51:00 -08001913 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001914 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001915 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001916 }
1917 }
1918 }
1919 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001920 }
Riley Andrews03414a12014-07-01 14:22:59 -07001921
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001922
Romain Guy0147a172017-06-01 13:53:56 -07001923 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001924
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 // Set the per-frame data
1926 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1927 auto& displayDevice = mDisplays[displayId];
1928 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001929
Dan Stoza9e56aa02015-11-02 13:00:03 -08001930 if (hwcId < 0) {
1931 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001932 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001933 if (colorMatrix != mPreviousColorMatrix) {
1934 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1935 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1936 "display %zd: %d", displayId, result);
1937 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1939 layer->setPerFrameData(displayDevice);
1940 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001941
1942 if (hasWideColorDisplay) {
1943 android_color_mode newColorMode;
1944 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1945
1946 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1947 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1948 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1949 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1950 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1951 }
1952 newColorMode = pickColorMode(newDataSpace);
1953
Thierry Strudel2924d012017-08-14 15:19:37 -07001954 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001955 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 }
1957
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001958 mPreviousColorMatrix = colorMatrix;
1959
Dan Stoza9e56aa02015-11-02 13:00:03 -08001960 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001961 auto& displayDevice = mDisplays[displayId];
1962 if (!displayDevice->isDisplayOn()) {
1963 continue;
1964 }
1965
1966 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001967 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1968 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001969 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001970}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001971
Mathias Agopiancd60f992012-08-16 16:28:27 -07001972void SurfaceFlinger::doComposition() {
1973 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 ALOGV("doComposition");
1975
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001976 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001977 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001978 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001979 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001980 // transform the dirty region into this screen's coordinate space
1981 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001982
1983 // repaint the framebuffer (if needed)
1984 doDisplayComposition(hw, dirtyRegion);
1985
Mathias Agopiancd60f992012-08-16 16:28:27 -07001986 hw->dirtyRegion.clear();
1987 hw->flip(hw->swapRegion);
1988 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001989 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001990 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001991 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001992}
1993
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001994void SurfaceFlinger::postFramebuffer()
1995{
Mathias Agopian841cde52012-03-01 15:44:37 -08001996 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001998
Mathias Agopiana44b0412011-10-16 18:46:35 -07001999 const nsecs_t now = systemTime();
2000 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002001
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2003 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002004 if (!displayDevice->isDisplayOn()) {
2005 continue;
2006 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002007 const auto hwcId = displayDevice->getHwcDisplayId();
2008 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002009 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002010 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002011 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002012 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002013 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2014 sp<Fence> releaseFence = Fence::NO_FENCE;
2015 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
2016 releaseFence = displayDevice->getClientTargetAcquireFence();
2017 } else {
2018 auto hwcLayer = layer->getHwcLayer(hwcId);
2019 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002020 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002021 layer->onLayerDisplayed(releaseFence);
2022 }
2023 if (hwcId >= 0) {
2024 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002025 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002026 }
2027
Mathias Agopiana44b0412011-10-16 18:46:35 -07002028 mLastSwapBufferTime = systemTime() - now;
2029 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002030
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002031 // |mStateLock| not needed as we are on the main thread
2032 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002033 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2034 logFrameStats();
2035 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002036}
2037
Mathias Agopian87baae12012-07-31 12:38:26 -07002038void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002039{
Mathias Agopian841cde52012-03-01 15:44:37 -08002040 ATRACE_CALL();
2041
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002042 // here we keep a copy of the drawing state (that is the state that's
2043 // going to be overwritten by handleTransactionLocked()) outside of
2044 // mStateLock so that the side-effects of the State assignment
2045 // don't happen with mStateLock held (which can cause deadlocks).
2046 State drawingState(mDrawingState);
2047
Mathias Agopianca4d3602011-05-19 15:38:14 -07002048 Mutex::Autolock _l(mStateLock);
2049 const nsecs_t now = systemTime();
2050 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002051
Mathias Agopianca4d3602011-05-19 15:38:14 -07002052 // Here we're guaranteed that some transaction flags are set
2053 // so we can call handleTransactionLocked() unconditionally.
2054 // We call getTransactionFlags(), which will also clear the flags,
2055 // with mStateLock held to guarantee that mCurrentState won't change
2056 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002057
Mathias Agopiane57f2922012-08-09 16:29:12 -07002058 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002059 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002060
Mathias Agopianca4d3602011-05-19 15:38:14 -07002061 mLastTransactionTime = systemTime() - now;
2062 mDebugInTransaction = 0;
2063 invalidateHwcGeometry();
2064 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002065}
2066
Mathias Agopian87baae12012-07-31 12:38:26 -07002067void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002068{
Dan Stoza7dde5992015-05-22 09:51:44 -07002069 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002070 mCurrentState.traverseInZOrder([](Layer* layer) {
2071 layer->notifyAvailableFrames();
2072 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002073
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002074 /*
2075 * Traversal of the children
2076 * (perform the transaction for each of them if needed)
2077 */
2078
Mathias Agopian3559b072012-08-15 13:46:03 -07002079 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002080 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002081 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002082 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002083
2084 const uint32_t flags = layer->doTransaction(0);
2085 if (flags & Layer::eVisibleRegion)
2086 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002087 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002088 }
2089
2090 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002091 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002092 */
2093
Mathias Agopiane57f2922012-08-09 16:29:12 -07002094 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002095 // here we take advantage of Vector's copy-on-write semantics to
2096 // improve performance by skipping the transaction entirely when
2097 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002098 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2099 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002100 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002101 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002102 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002103 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002104
2105 // find the displays that were removed
2106 // (ie: in drawing state but not in current state)
2107 // also handle displays that changed
2108 // (ie: displays that are in both lists)
2109 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002110 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2111 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002112 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002113 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002114 // Call makeCurrent() on the primary display so we can
2115 // be sure that nothing associated with this display
2116 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002117 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002118 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002119 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002120 if (hw != NULL)
2121 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002122 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002123 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002124 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002125 } else {
2126 ALOGW("trying to remove the main display");
2127 }
2128 } else {
2129 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002130 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002131 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002132 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2133 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002134 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002135 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002136 // recreating the DisplayDevice, so we just remove it
2137 // from the drawing state, so that it get re-added
2138 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002139 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002140 if (hw != NULL)
2141 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002142 mDisplays.removeItem(display);
2143 mDrawingState.displays.removeItemsAt(i);
2144 dc--; i--;
2145 // at this point we must loop to the next item
2146 continue;
2147 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002148
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002149 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002150 if (disp != NULL) {
2151 if (state.layerStack != draw[i].layerStack) {
2152 disp->setLayerStack(state.layerStack);
2153 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002154 if ((state.orientation != draw[i].orientation)
2155 || (state.viewport != draw[i].viewport)
2156 || (state.frame != draw[i].frame))
2157 {
2158 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002159 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002160 }
Michael Lentine47e45402014-07-18 15:34:25 -07002161 if (state.width != draw[i].width || state.height != draw[i].height) {
2162 disp->setDisplaySize(state.width, state.height);
2163 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002164 }
2165 }
2166 }
2167
2168 // find displays that were added
2169 // (ie: in current state but not in drawing state)
2170 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002171 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002172 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002173
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002174 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002175 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002176 sp<IGraphicBufferProducer> bqProducer;
2177 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002178 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002179
Dan Stoza9e56aa02015-11-02 13:00:03 -08002180 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002181 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002182 // Virtual displays without a surface are dormant:
2183 // they have external state (layer stack, projection,
2184 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002185 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002186
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002187 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002188 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002189 int width = 0;
2190 int status = state.surface->query(
2191 NATIVE_WINDOW_WIDTH, &width);
2192 ALOGE_IF(status != NO_ERROR,
2193 "Unable to query width (%d)", status);
2194 int height = 0;
2195 status = state.surface->query(
2196 NATIVE_WINDOW_HEIGHT, &height);
2197 ALOGE_IF(status != NO_ERROR,
2198 "Unable to query height (%d)", status);
2199 int intFormat = 0;
2200 status = state.surface->query(
2201 NATIVE_WINDOW_FORMAT, &intFormat);
2202 ALOGE_IF(status != NO_ERROR,
2203 "Unable to query format (%d)", status);
2204 auto format = static_cast<android_pixel_format_t>(
2205 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002206
Dan Stoza8cf150a2016-08-02 10:27:31 -07002207 mHwc->allocateVirtualDisplay(width, height, &format,
2208 &hwcId);
2209 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002210
Dan Stoza5cf424b2016-05-20 14:02:39 -07002211 // TODO: Plumb requested format back up to consumer
2212
Dan Stoza9e56aa02015-11-02 13:00:03 -08002213 sp<VirtualDisplaySurface> vds =
2214 new VirtualDisplaySurface(*mHwc,
2215 hwcId, state.surface, bqProducer,
2216 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002217
2218 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002219 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002220 }
2221 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002222 ALOGE_IF(state.surface!=NULL,
2223 "adding a supported display, but rendering "
2224 "surface is provided (%p), ignoring it",
2225 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002226
2227 hwcId = state.type;
2228 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2229 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002230 }
2231
2232 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002233 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002234 sp<DisplayDevice> hw =
2235 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2236 dispSurface, producer,
2237 mRenderEngine->getEGLConfig(),
2238 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002239 hw->setLayerStack(state.layerStack);
2240 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002241 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002242 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002243 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002244 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002245 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002246 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002247 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002248 }
2249 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002250 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002251 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002252
Mathias Agopian84300952012-11-21 16:02:13 -08002253 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2254 // The transform hint might have changed for some layers
2255 // (either because a display has changed, or because a layer
2256 // as changed).
2257 //
2258 // Walk through all the layers in currentLayers,
2259 // and update their transform hint.
2260 //
2261 // If a layer is visible only on a single display, then that
2262 // display is used to calculate the hint, otherwise we use the
2263 // default display.
2264 //
2265 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2266 // the hint is set before we acquire a buffer from the surface texture.
2267 //
2268 // NOTE: layer transactions have taken place already, so we use their
2269 // drawing state. However, SurfaceFlinger's own transaction has not
2270 // happened yet, so we must use the current state layer list
2271 // (soon to become the drawing state list).
2272 //
2273 sp<const DisplayDevice> disp;
2274 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002275 bool first = true;
2276 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002277 // NOTE: we rely on the fact that layers are sorted by
2278 // layerStack first (so we don't have to traverse the list
2279 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002280 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002281 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002282 currentlayerStack = layerStack;
2283 // figure out if this layerstack is mirrored
2284 // (more than one display) if so, pick the default display,
2285 // if not, pick the only display it's on.
2286 disp.clear();
2287 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2288 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002289 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002290 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002291 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002292 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002293 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002294 break;
2295 }
2296 }
2297 }
2298 }
Chet Haase91d25932013-04-11 15:24:55 -07002299 if (disp == NULL) {
2300 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2301 // redraw after transform hint changes. See bug 8508397.
2302
2303 // could be null when this layer is using a layerStack
2304 // that is not visible on any display. Also can occur at
2305 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002306 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002307 }
Chet Haase91d25932013-04-11 15:24:55 -07002308 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002309
2310 first = false;
2311 });
Mathias Agopian84300952012-11-21 16:02:13 -08002312 }
2313
2314
Mathias Agopian3559b072012-08-15 13:46:03 -07002315 /*
2316 * Perform our own transaction if needed
2317 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002318
2319 if (mLayersAdded) {
2320 mLayersAdded = false;
2321 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002322 mVisibleRegionsDirty = true;
2323 }
2324
2325 // some layers might have been removed, so
2326 // we need to update the regions they're exposing.
2327 if (mLayersRemoved) {
2328 mLayersRemoved = false;
2329 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002330 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002331 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002332 // this layer is not visible anymore
2333 // TODO: we could traverse the tree from front to back and
2334 // compute the actual visible region
2335 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002336 Region visibleReg;
2337 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002338 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002339 }
Robert Carr2047fae2016-11-28 14:09:09 -08002340 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341 }
2342
2343 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002344
2345 updateCursorAsync();
2346}
2347
2348void SurfaceFlinger::updateCursorAsync()
2349{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002350 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2351 auto& displayDevice = mDisplays[displayId];
2352 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002353 continue;
2354 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002355
2356 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2357 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002358 }
2359 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002360}
2361
2362void SurfaceFlinger::commitTransaction()
2363{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002364 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002365 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002366 for (const auto& l : mLayersPendingRemoval) {
2367 recordBufferingStats(l->getName().string(),
2368 l->getOccupancyHistory(true));
2369 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002370 }
2371 mLayersPendingRemoval.clear();
2372 }
2373
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002374 // If this transaction is part of a window animation then the next frame
2375 // we composite should be considered an animation as well.
2376 mAnimCompositionPending = mAnimTransactionPending;
2377
Mathias Agopian4fec8732012-06-29 14:12:52 -07002378 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002379 mDrawingState.traverseInZOrder([](Layer* layer) {
2380 layer->commitChildList();
2381 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002382 mTransactionPending = false;
2383 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002384 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002385}
2386
Chia-I Wuab0c3192017-08-01 11:29:00 -07002387void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002388 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002389{
Mathias Agopian841cde52012-03-01 15:44:37 -08002390 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002391 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002392
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002393 Region aboveOpaqueLayers;
2394 Region aboveCoveredLayers;
2395 Region dirty;
2396
Mathias Agopian87baae12012-07-31 12:38:26 -07002397 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002398
Robert Carr2047fae2016-11-28 14:09:09 -08002399 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002400 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002401 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002402
Jesse Hall01e29052013-02-19 16:13:35 -08002403 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002404 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002405 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002406
Mathias Agopianab028732010-03-16 16:41:46 -07002407 /*
2408 * opaqueRegion: area of a surface that is fully opaque.
2409 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002410 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002411
2412 /*
2413 * visibleRegion: area of a surface that is visible on screen
2414 * and not fully transparent. This is essentially the layer's
2415 * footprint minus the opaque regions above it.
2416 * Areas covered by a translucent surface are considered visible.
2417 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002418 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002419
2420 /*
2421 * coveredRegion: area of a surface that is covered by all
2422 * visible regions above it (which includes the translucent areas).
2423 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002424 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002425
Jesse Halla8026d22012-09-25 13:25:04 -07002426 /*
2427 * transparentRegion: area of a surface that is hinted to be completely
2428 * transparent. This is only used to tell when the layer has no visible
2429 * non-transparent regions and can be removed from the layer list. It
2430 * does not affect the visibleRegion of this layer or any layers
2431 * beneath it. The hint may not be correct if apps don't respect the
2432 * SurfaceView restrictions (which, sadly, some don't).
2433 */
2434 Region transparentRegion;
2435
Mathias Agopianab028732010-03-16 16:41:46 -07002436
2437 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002438 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002439 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002440 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002441 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002442 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002443 if (!visibleRegion.isEmpty()) {
2444 // Remove the transparent area from the visible region
2445 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002446 if (tr.preserveRects()) {
2447 // transform the transparent region
2448 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002449 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002450 // transformation too complex, can't do the
2451 // transparent region optimization.
2452 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002453 }
Mathias Agopianab028732010-03-16 16:41:46 -07002454 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455
Mathias Agopianab028732010-03-16 16:41:46 -07002456 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002457 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002458 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002459 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2460 // the opaque region is the layer's footprint
2461 opaqueRegion = visibleRegion;
2462 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463 }
2464 }
2465
Mathias Agopianab028732010-03-16 16:41:46 -07002466 // Clip the covered region to the visible region
2467 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2468
2469 // Update aboveCoveredLayers for next (lower) layer
2470 aboveCoveredLayers.orSelf(visibleRegion);
2471
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002472 // subtract the opaque region covered by the layers above us
2473 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002474
2475 // compute this layer's dirty region
2476 if (layer->contentDirty) {
2477 // we need to invalidate the whole region
2478 dirty = visibleRegion;
2479 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002480 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002481 layer->contentDirty = false;
2482 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002483 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002484 * the exposed region consists of two components:
2485 * 1) what's VISIBLE now and was COVERED before
2486 * 2) what's EXPOSED now less what was EXPOSED before
2487 *
2488 * note that (1) is conservative, we start with the whole
2489 * visible region but only keep what used to be covered by
2490 * something -- which mean it may have been exposed.
2491 *
2492 * (2) handles areas that were not covered by anything but got
2493 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002494 */
Mathias Agopianab028732010-03-16 16:41:46 -07002495 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002496 const Region oldVisibleRegion = layer->visibleRegion;
2497 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002498 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2499 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500 }
2501 dirty.subtractSelf(aboveOpaqueLayers);
2502
2503 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002504 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002505
Mathias Agopianab028732010-03-16 16:41:46 -07002506 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002508
Jesse Halla8026d22012-09-25 13:25:04 -07002509 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510 layer->setVisibleRegion(visibleRegion);
2511 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002512 layer->setVisibleNonTransparentRegion(
2513 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002514 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515
Mathias Agopian87baae12012-07-31 12:38:26 -07002516 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517}
2518
Chia-I Wuab0c3192017-08-01 11:29:00 -07002519void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002520 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002521 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002522 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002523 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002524 }
2525 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002526}
2527
Dan Stoza6b9454d2014-11-07 16:00:59 -08002528bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002529{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002530 ALOGV("handlePageFlip");
2531
Brian Andersond6927fb2016-07-23 23:37:30 -07002532 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002533
Mathias Agopian4fec8732012-06-29 14:12:52 -07002534 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002535 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002536 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002537
2538 // Store the set of layers that need updates. This set must not change as
2539 // buffers are being latched, as this could result in a deadlock.
2540 // Example: Two producers share the same command stream and:
2541 // 1.) Layer 0 is latched
2542 // 2.) Layer 0 gets a new frame
2543 // 2.) Layer 1 gets a new frame
2544 // 3.) Layer 1 is latched.
2545 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2546 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002547 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002548 if (layer->hasQueuedFrame()) {
2549 frameQueued = true;
2550 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002551 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002552 } else {
2553 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002554 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002555 } else {
2556 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002557 }
Robert Carr2047fae2016-11-28 14:09:09 -08002558 });
2559
Dan Stoza9e56aa02015-11-02 13:00:03 -08002560 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002561 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002562 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002563 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002564 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002565 newDataLatched = true;
2566 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002567 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002568
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002569 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002570
2571 // If we will need to wake up at some time in the future to deal with a
2572 // queued frame that shouldn't be displayed during this vsync period, wake
2573 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002574 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002575 signalLayerUpdate();
2576 }
2577
2578 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002579 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580}
2581
Mathias Agopianad456f92011-01-13 17:53:01 -08002582void SurfaceFlinger::invalidateHwcGeometry()
2583{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002584 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002585}
2586
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002587
Fabien Sanglard830b8472016-11-30 16:35:58 -08002588void SurfaceFlinger::doDisplayComposition(
2589 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002590 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591{
Dan Stoza71433162014-02-04 16:22:36 -08002592 // We only need to actually compose the display if:
2593 // 1) It is being handled by hardware composer, which may need this to
2594 // keep its virtual display state machine in sync, or
2595 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002596 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002597 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002598 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002599 return;
2600 }
2601
Dan Stoza9e56aa02015-11-02 13:00:03 -08002602 ALOGV("doDisplayComposition");
2603
Mathias Agopian87baae12012-07-31 12:38:26 -07002604 Region dirtyRegion(inDirtyRegion);
2605
Mathias Agopianb8a55602009-06-26 19:06:36 -07002606 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002607 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608
Fabien Sanglard830b8472016-11-30 16:35:58 -08002609 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002610 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002611 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2612 // takes a rectangle, we must make sure to update that whole
2613 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002614 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002615 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002616 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002617 // We need to redraw the rectangle that will be updated
2618 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002619 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002620 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002621 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002622 } else {
2623 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002624 dirtyRegion.set(displayDevice->bounds());
2625 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002626 }
2627 }
2628
Fabien Sanglard830b8472016-11-30 16:35:58 -08002629 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002631 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002632 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002633
2634 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002635 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636}
2637
Dan Stoza9e56aa02015-11-02 13:00:03 -08002638bool SurfaceFlinger::doComposeSurfaces(
2639 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002640{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002641 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002642
Dan Stoza9e56aa02015-11-02 13:00:03 -08002643 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002644
2645 mat4 oldColorMatrix;
2646 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2647 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2648 if (applyColorMatrix) {
2649 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2650 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2651 }
2652
Dan Stoza9e56aa02015-11-02 13:00:03 -08002653 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2654 if (hasClientComposition) {
2655 ALOGV("hasClientComposition");
2656
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002657#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01002658 mRenderEngine->setWideColor(
2659 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2660 mRenderEngine->setColorMode(mForceNativeColorMode ?
2661 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002662#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002664 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002665 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002666 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002667
2668 // |mStateLock| not needed as we are on the main thread
2669 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002670 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2671 }
2672 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002673 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002674
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002675 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002676 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2677 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002678 // when using overlays, we assume a fully transparent framebuffer
2679 // NOTE: we could reduce how much we need to clear, for instance
2680 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002681 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002682 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002683 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002684 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002685 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002686 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002687
2688 // we remove the scissor part
2689 // we're left with the letterbox region
2690 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002691 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002692
2693 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002694 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002695
2696 // but limit it to the dirty region
2697 region.andSelf(dirty);
2698
Mathias Agopianb9494d52012-04-18 02:28:45 -07002699 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002700 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002701 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002702 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002703 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002704 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002705
Dan Stoza9e56aa02015-11-02 13:00:03 -08002706 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002707 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002708 // scissor on the main display. It should never be needed
2709 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002710 const Rect& bounds(displayDevice->getBounds());
2711 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002712 if (scissor != bounds) {
2713 // scissor doesn't match the screen's dimensions, so we
2714 // need to clear everything outside of it and enable
2715 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002716
Mathias Agopianf45c5102012-10-24 16:29:17 -07002717 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002718 const uint32_t height = displayDevice->getHeight();
2719 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002720 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002721 }
2722 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002723 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002724
Mathias Agopian85d751c2012-08-29 16:59:24 -07002725 /*
2726 * and then, render the layers targeted at the framebuffer
2727 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002728
Dan Stoza9e56aa02015-11-02 13:00:03 -08002729 ALOGV("Rendering client layers");
2730 const Transform& displayTransform = displayDevice->getTransform();
2731 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002732 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002733 bool firstLayer = true;
2734 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2735 const Region clip(dirty.intersect(
2736 displayTransform.transform(layer->visibleRegion)));
2737 ALOGV("Layer: %s", layer->getName().string());
2738 ALOGV(" Composition type: %s",
2739 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002740 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002741 switch (layer->getCompositionType(hwcId)) {
2742 case HWC2::Composition::Cursor:
2743 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002744 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002745 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002746 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002747 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2748 layer->isOpaque(state) && (state.alpha == 1.0f)
2749 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002750 // never clear the very first layer since we're
2751 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002752 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002753 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002754 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002755 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002756 case HWC2::Composition::Client: {
2757 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002758 break;
2759 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002760 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002761 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002762 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002763 } else {
2764 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002765 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002766 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002767 }
2768 } else {
2769 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002770 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002771 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002772 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002773 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002774 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002775 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002776 }
2777 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002778
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002779 if (applyColorMatrix) {
2780 getRenderEngine().setupColorTransform(oldColorMatrix);
2781 }
2782
Mathias Agopianf45c5102012-10-24 16:29:17 -07002783 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002784 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002785 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786}
2787
Fabien Sanglard830b8472016-11-30 16:35:58 -08002788void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2789 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002790 RenderEngine& engine(getRenderEngine());
2791 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792}
2793
Dan Stoza7d89d062015-04-30 13:29:25 -07002794status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002795 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002796 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002797 const sp<Layer>& lbc,
2798 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002799{
Dan Stoza7d89d062015-04-30 13:29:25 -07002800 // add this layer to the current state list
2801 {
2802 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002803 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002804 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2805 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002806 return NO_MEMORY;
2807 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002808 if (parent == nullptr) {
2809 mCurrentState.layersSortedByZ.add(lbc);
2810 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002811 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2812 ALOGE("addClientLayer called with a removed parent");
2813 return NAME_NOT_FOUND;
2814 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002815 parent->addChild(lbc);
2816 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002817
Dan Stoza7d89d062015-04-30 13:29:25 -07002818 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002819 mLayersAdded = true;
2820 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002821 }
2822
Mathias Agopian96f08192010-06-02 23:28:45 -07002823 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002824 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002825
Dan Stoza7d89d062015-04-30 13:29:25 -07002826 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002827}
2828
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002829status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002830 Mutex::Autolock _l(mStateLock);
2831
Robert Carr1f0a16a2016-10-24 16:27:39 -07002832 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002833 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002834 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002835 if (topLevelOnly) {
2836 return NO_ERROR;
2837 }
2838
Chia-I Wu98f1c102017-05-30 14:54:08 -07002839 sp<Layer> ancestor = p;
2840 while (ancestor->getParent() != nullptr) {
2841 ancestor = ancestor->getParent();
2842 }
2843 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2844 ALOGE("removeLayer called with a layer whose parent has been removed");
2845 return NAME_NOT_FOUND;
2846 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002847
2848 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002849 } else {
2850 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002851 }
2852
Robert Carr136e2f62017-02-08 17:54:29 -08002853 // As a matter of normal operation, the LayerCleaner will produce a second
2854 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2855 // so we will succeed in promoting it, but it's already been removed
2856 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2857 // otherwise something has gone wrong and we are leaking the layer.
2858 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002859 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2860 layer->getName().string(),
2861 (p != nullptr) ? p->getName().string() : "no-parent");
2862 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002863 } else if (index < 0) {
2864 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002865 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002866
Chia-I Wuc6657022017-08-15 11:18:17 -07002867 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002868 mLayersPendingRemoval.add(layer);
2869 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002870 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002871 setTransactionFlags(eTransactionNeeded);
2872 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873}
2874
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002875uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002876 return android_atomic_release_load(&mTransactionFlags);
2877}
2878
Mathias Agopian3f844832013-08-07 21:24:32 -07002879uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2881}
2882
Mathias Agopian3f844832013-08-07 21:24:32 -07002883uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2885 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002886 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 }
2888 return old;
2889}
2890
Mathias Agopian8b33f032012-07-24 20:43:54 -07002891void SurfaceFlinger::setTransactionState(
2892 const Vector<ComposerState>& state,
2893 const Vector<DisplayState>& displays,
2894 uint32_t flags)
2895{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002896 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002897 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002898 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002899
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002900 if (flags & eAnimation) {
2901 // For window updates that are part of an animation we must wait for
2902 // previous animation "frames" to be handled.
2903 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002904 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002905 if (CC_UNLIKELY(err != NO_ERROR)) {
2906 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002907 // caller after a few seconds.
2908 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2909 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002910 mAnimTransactionPending = false;
2911 break;
2912 }
2913 }
2914 }
2915
Mathias Agopiane57f2922012-08-09 16:29:12 -07002916 size_t count = displays.size();
2917 for (size_t i=0 ; i<count ; i++) {
2918 const DisplayState& s(displays[i]);
2919 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002920 }
2921
Mathias Agopiane57f2922012-08-09 16:29:12 -07002922 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002923 for (size_t i=0 ; i<count ; i++) {
2924 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002925 // Here we need to check that the interface we're given is indeed
2926 // one of our own. A malicious client could give us a NULL
2927 // IInterface, or one of its own or even one of our own but a
2928 // different type. All these situations would cause us to crash.
2929 //
2930 // NOTE: it would be better to use RTTI as we could directly check
2931 // that we have a Client*. however, RTTI is disabled in Android.
2932 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002933 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002934 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002935 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002936 sp<Client> client( static_cast<Client *>(s.client.get()) );
2937 transactionFlags |= setClientStateLocked(client, s.state);
2938 }
2939 }
2940 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002941 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002942
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002943 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2944 // anyway. This can be used as a flush mechanism for previous async transactions.
2945 // Empty animation transaction can be used to simulate back-pressure, so also force a
2946 // transaction for empty animation transactions.
2947 if (transactionFlags == 0 &&
2948 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002949 transactionFlags = eTransactionNeeded;
2950 }
2951
Mathias Agopian386aa982011-11-07 21:58:03 -08002952 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002953 if (mInterceptor.isEnabled()) {
2954 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2955 }
Irvel468051e2016-06-13 16:44:44 -07002956
Mathias Agopian386aa982011-11-07 21:58:03 -08002957 // this triggers the transaction
2958 setTransactionFlags(transactionFlags);
2959
2960 // if this is a synchronous transaction, wait for it to take effect
2961 // before returning.
2962 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002963 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002964 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002965 if (flags & eAnimation) {
2966 mAnimTransactionPending = true;
2967 }
2968 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002969 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2970 if (CC_UNLIKELY(err != NO_ERROR)) {
2971 // just in case something goes wrong in SF, return to the
2972 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002973 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2974 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002975 break;
2976 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002977 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978 }
2979}
2980
Mathias Agopiane57f2922012-08-09 16:29:12 -07002981uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2982{
Jesse Hall9a143922012-10-04 16:29:19 -07002983 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2984 if (dpyIdx < 0)
2985 return 0;
2986
Mathias Agopiane57f2922012-08-09 16:29:12 -07002987 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002988 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002989 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002990 const uint32_t what = s.what;
2991 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002992 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002993 disp.surface = s.surface;
2994 flags |= eDisplayTransactionNeeded;
2995 }
2996 }
2997 if (what & DisplayState::eLayerStackChanged) {
2998 if (disp.layerStack != s.layerStack) {
2999 disp.layerStack = s.layerStack;
3000 flags |= eDisplayTransactionNeeded;
3001 }
3002 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003003 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003004 if (disp.orientation != s.orientation) {
3005 disp.orientation = s.orientation;
3006 flags |= eDisplayTransactionNeeded;
3007 }
3008 if (disp.frame != s.frame) {
3009 disp.frame = s.frame;
3010 flags |= eDisplayTransactionNeeded;
3011 }
3012 if (disp.viewport != s.viewport) {
3013 disp.viewport = s.viewport;
3014 flags |= eDisplayTransactionNeeded;
3015 }
3016 }
Michael Lentine47e45402014-07-18 15:34:25 -07003017 if (what & DisplayState::eDisplaySizeChanged) {
3018 if (disp.width != s.width) {
3019 disp.width = s.width;
3020 flags |= eDisplayTransactionNeeded;
3021 }
3022 if (disp.height != s.height) {
3023 disp.height = s.height;
3024 flags |= eDisplayTransactionNeeded;
3025 }
3026 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003027 }
3028 return flags;
3029}
3030
3031uint32_t SurfaceFlinger::setClientStateLocked(
3032 const sp<Client>& client,
3033 const layer_state_t& s)
3034{
3035 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003036 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003037 if (layer != 0) {
3038 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003039 bool geometryAppliesWithResize =
3040 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003041 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003042 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003043 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003044 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003045 }
3046 if (what & layer_state_t::eLayerChanged) {
3047 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003048 const auto& p = layer->getParent();
3049 if (p == nullptr) {
3050 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3051 if (layer->setLayer(s.z) && idx >= 0) {
3052 mCurrentState.layersSortedByZ.removeAt(idx);
3053 mCurrentState.layersSortedByZ.add(layer);
3054 // we need traversal (state changed)
3055 // AND transaction (list changed)
3056 flags |= eTransactionNeeded|eTraversalNeeded;
3057 }
3058 } else {
3059 if (p->setChildLayer(layer, s.z)) {
3060 flags |= eTransactionNeeded|eTraversalNeeded;
3061 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003062 }
3063 }
Robert Carrdb66e622017-04-10 16:55:57 -07003064 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003065 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003066 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003067 mCurrentState.layersSortedByZ.removeAt(idx);
3068 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003069 flags |= eTransactionNeeded|eTraversalNeeded;
3070 }
3071 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003072 if (what & layer_state_t::eSizeChanged) {
3073 if (layer->setSize(s.w, s.h)) {
3074 flags |= eTraversalNeeded;
3075 }
3076 }
3077 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003078 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003079 flags |= eTraversalNeeded;
3080 }
3081 if (what & layer_state_t::eMatrixChanged) {
3082 if (layer->setMatrix(s.matrix))
3083 flags |= eTraversalNeeded;
3084 }
3085 if (what & layer_state_t::eTransparentRegionChanged) {
3086 if (layer->setTransparentRegionHint(s.transparentRegion))
3087 flags |= eTraversalNeeded;
3088 }
Dan Stoza23116082015-06-18 14:58:39 -07003089 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003090 if (layer->setFlags(s.flags, s.mask))
3091 flags |= eTraversalNeeded;
3092 }
3093 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003094 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003095 flags |= eTraversalNeeded;
3096 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003097 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003098 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003099 flags |= eTraversalNeeded;
3100 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003101 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003102 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003103 // We only allow setting layer stacks for top level layers,
3104 // everything else inherits layer stack from its parent.
3105 if (layer->hasParent()) {
3106 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3107 layer->getName().string());
3108 } else if (idx < 0) {
3109 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3110 "that also does not appear in the top level layer list. Something"
3111 " has gone wrong.", layer->getName().string());
3112 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003113 mCurrentState.layersSortedByZ.removeAt(idx);
3114 mCurrentState.layersSortedByZ.add(layer);
3115 // we need traversal (state changed)
3116 // AND transaction (list changed)
3117 flags |= eTransactionNeeded|eTraversalNeeded;
3118 }
3119 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003120 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003121 if (s.barrierHandle != nullptr) {
3122 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3123 } else if (s.barrierGbp != nullptr) {
3124 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3125 if (authenticateSurfaceTextureLocked(gbp)) {
3126 const auto& otherLayer =
3127 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3128 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3129 } else {
3130 ALOGE("Attempt to defer transaction to to an"
3131 " unrecognized GraphicBufferProducer");
3132 }
3133 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003134 // We don't trigger a traversal here because if no other state is
3135 // changed, we don't want this to cause any more work
3136 }
Robert Carr1db73f62016-12-21 12:58:51 -08003137 if (what & layer_state_t::eReparentChildren) {
3138 if (layer->reparentChildren(s.reparentHandle)) {
3139 flags |= eTransactionNeeded|eTraversalNeeded;
3140 }
3141 }
Robert Carr9524cb32017-02-13 11:32:32 -08003142 if (what & layer_state_t::eDetachChildren) {
3143 layer->detachChildren();
3144 }
Robert Carrc3574f72016-03-24 12:19:32 -07003145 if (what & layer_state_t::eOverrideScalingModeChanged) {
3146 layer->setOverrideScalingMode(s.overrideScalingMode);
3147 // We don't trigger a traversal here because if no other state is
3148 // changed, we don't want this to cause any more work
3149 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003150 }
3151 return flags;
3152}
3153
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003154status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003155 const String8& name,
3156 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003157 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003158 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3159 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003161 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003162 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003163 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003164 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003165 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003166
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003167 status_t result = NO_ERROR;
3168
3169 sp<Layer> layer;
3170
Cody Northropbc755282017-03-31 12:00:08 -06003171 String8 uniqueName = getUniqueLayerName(name);
3172
Mathias Agopian3165cc22012-08-08 19:42:09 -07003173 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3174 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003175 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003176 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003177 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003179 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003180 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003181 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003182 handle, gbp, &layer);
3183 break;
3184 default:
3185 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186 break;
3187 }
3188
Dan Stoza7d89d062015-04-30 13:29:25 -07003189 if (result != NO_ERROR) {
3190 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003191 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003192
Chia-I Wuab0c3192017-08-01 11:29:00 -07003193 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3194 // TODO b/64227542
3195 if (windowType == 441731) {
3196 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3197 layer->setPrimaryDisplayOnly();
3198 }
3199
Albert Chaulk479c60c2017-01-27 14:21:34 -05003200 layer->setInfo(windowType, ownerUid);
3201
Robert Carr1f0a16a2016-10-24 16:27:39 -07003202 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003203 if (result != NO_ERROR) {
3204 return result;
3205 }
Irvelffc9efc2016-07-27 15:16:37 -07003206 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003207
3208 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003209 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210}
3211
Cody Northropbc755282017-03-31 12:00:08 -06003212String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3213{
3214 bool matchFound = true;
3215 uint32_t dupeCounter = 0;
3216
3217 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3218 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3219
3220 // Loop over layers until we're sure there is no matching name
3221 while (matchFound) {
3222 matchFound = false;
3223 mDrawingState.traverseInZOrder([&](Layer* layer) {
3224 if (layer->getName() == uniqueName) {
3225 matchFound = true;
3226 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3227 }
3228 });
3229 }
3230
3231 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3232
3233 return uniqueName;
3234}
3235
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003236status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3237 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3238 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239{
3240 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003241 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242 case PIXEL_FORMAT_TRANSPARENT:
3243 case PIXEL_FORMAT_TRANSLUCENT:
3244 format = PIXEL_FORMAT_RGBA_8888;
3245 break;
3246 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003247 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248 break;
3249 }
3250
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003251 *outLayer = new Layer(this, client, name, w, h, flags);
3252 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3253 if (err == NO_ERROR) {
3254 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003255 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003256 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003257
3258 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3259 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003260}
3261
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003262status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3263 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3264 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003266 *outLayer = new LayerDim(this, client, name, w, h, flags);
3267 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003268 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003269 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003270}
3271
Mathias Agopianac9fa422013-02-11 16:40:36 -08003272status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003273{
Robert Carr9524cb32017-02-13 11:32:32 -08003274 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003275 status_t err = NO_ERROR;
3276 sp<Layer> l(client->getLayerUser(handle));
3277 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003278 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003279 err = removeLayer(l);
3280 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3281 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003282 }
3283 return err;
3284}
3285
Mathias Agopian13127d82013-03-05 17:47:11 -08003286status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003287{
Mathias Agopian67106042013-03-14 19:18:13 -07003288 // called by ~LayerCleaner() when all references to the IBinder (handle)
3289 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003290 sp<Layer> l = layer.promote();
3291 if (l == nullptr) {
3292 // The layer has already been removed, carry on
3293 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003294 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003295 // If we have a parent, then we can continue to live as long as it does.
3296 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003297}
3298
Mathias Agopianb60314a2012-04-10 22:09:54 -07003299// ---------------------------------------------------------------------------
3300
Andy McFadden13a082e2012-08-24 10:16:42 -07003301void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003302 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003303 Vector<ComposerState> state;
3304 Vector<DisplayState> displays;
3305 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003306 d.what = DisplayState::eDisplayProjectionChanged |
3307 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003308 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003309 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003310 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003311 d.frame.makeInvalid();
3312 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003313 d.width = 0;
3314 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003315 displays.add(d);
3316 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003317 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3318 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003319
Dan Stoza9e56aa02015-11-02 13:00:03 -08003320 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3321 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003322 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003323
Brian Andersond0010582017-03-07 13:20:31 -08003324 // Use phase of 0 since phase is not known.
3325 // Use latency of 0, which will snap to the ideal latency.
3326 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003327}
3328
3329void SurfaceFlinger::initializeDisplays() {
3330 class MessageScreenInitialized : public MessageBase {
3331 SurfaceFlinger* flinger;
3332 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003333 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003334 virtual bool handler() {
3335 flinger->onInitializeDisplays();
3336 return true;
3337 }
3338 };
3339 sp<MessageBase> msg = new MessageScreenInitialized(this);
3340 postMessageAsync(msg); // we may be called from main thread, use async message
3341}
3342
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003343void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003344 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003345 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3346 this);
3347 int32_t type = hw->getDisplayType();
3348 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003349
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003350 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003351 return;
3352 }
3353
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003354 hw->setPowerMode(mode);
3355 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3356 ALOGW("Trying to set power mode for virtual display");
3357 return;
3358 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003359
Irvelffc9efc2016-07-27 15:16:37 -07003360 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003361 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003362 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3363 if (idx < 0) {
3364 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3365 return;
3366 }
3367 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3368 }
3369
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003370 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003371 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003372 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003373 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3374 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003375 // FIXME: eventthread only knows about the main display right now
3376 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003377 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003378 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003379
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003380 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003381 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003382 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003383
3384 struct sched_param param = {0};
3385 param.sched_priority = 1;
3386 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3387 ALOGW("Couldn't set SCHED_FIFO on display on");
3388 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003389 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003390 // Turn off the display
3391 struct sched_param param = {0};
3392 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3393 ALOGW("Couldn't set SCHED_OTHER on display off");
3394 }
3395
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003396 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003397 disableHardwareVsync(true); // also cancels any in-progress resync
3398
Mathias Agopiancde87a32012-09-13 14:09:01 -07003399 // FIXME: eventthread only knows about the main display right now
3400 mEventThread->onScreenReleased();
3401 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003402
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003403 getHwComposer().setPowerMode(type, mode);
3404 mVisibleRegionsDirty = true;
3405 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003406 } else if (mode == HWC_POWER_MODE_DOZE ||
3407 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003408 // Update display while dozing
3409 getHwComposer().setPowerMode(type, mode);
3410 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3411 // FIXME: eventthread only knows about the main display right now
3412 mEventThread->onScreenAcquired();
3413 resyncToHardwareVsync(true);
3414 }
3415 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3416 // Leave display going to doze
3417 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3418 disableHardwareVsync(true); // also cancels any in-progress resync
3419 // FIXME: eventthread only knows about the main display right now
3420 mEventThread->onScreenReleased();
3421 }
3422 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003423 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003424 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003425 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003426 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003427}
3428
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003429void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3430 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003431 SurfaceFlinger& mFlinger;
3432 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003433 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003434 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003435 MessageSetPowerMode(SurfaceFlinger& flinger,
3436 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3437 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003438 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003439 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003440 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003441 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003442 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003443 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003444 ALOGW("Attempt to set power mode = %d for virtual display",
3445 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003446 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003447 mFlinger.setPowerModeInternal(
3448 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003449 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003450 return true;
3451 }
3452 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003453 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003454 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003455}
3456
3457// ---------------------------------------------------------------------------
3458
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003459status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3460{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003461 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003462
Mathias Agopianbd115332013-04-18 16:41:04 -07003463 IPCThreadState* ipc = IPCThreadState::self();
3464 const int pid = ipc->getCallingPid();
3465 const int uid = ipc->getCallingUid();
3466 if ((uid != AID_SHELL) &&
3467 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003468 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003469 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003470 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003471 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003472 // (this would indicate SF is stuck, but we want to be able to
3473 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003474 status_t err = mStateLock.timedLock(s2ns(1));
3475 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003476 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003477 result.appendFormat(
3478 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3479 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003480 }
3481
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003482 bool dumpAll = true;
3483 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003484 size_t numArgs = args.size();
3485 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003486 if ((index < numArgs) &&
3487 (args[index] == String16("--list"))) {
3488 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003489 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003490 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003491 }
3492
3493 if ((index < numArgs) &&
3494 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003495 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003496 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003497 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003498 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003499
3500 if ((index < numArgs) &&
3501 (args[index] == String16("--latency-clear"))) {
3502 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003503 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003504 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003505 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003506
3507 if ((index < numArgs) &&
3508 (args[index] == String16("--dispsync"))) {
3509 index++;
3510 mPrimaryDispSync.dump(result);
3511 dumpAll = false;
3512 }
Dan Stozab90cf072015-03-05 11:05:59 -08003513
3514 if ((index < numArgs) &&
3515 (args[index] == String16("--static-screen"))) {
3516 index++;
3517 dumpStaticScreenStats(result);
3518 dumpAll = false;
3519 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003520
3521 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003522 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003523 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003524 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003525 dumpAll = false;
3526 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003527
3528 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3529 index++;
3530 dumpWideColorInfo(result);
3531 dumpAll = false;
3532 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003533 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003534
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003535 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003536 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003537 }
3538
Mathias Agopian9795c422009-08-26 16:36:26 -07003539 if (locked) {
3540 mStateLock.unlock();
3541 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003542 }
3543 write(fd, result.string(), result.size());
3544 return NO_ERROR;
3545}
3546
Dan Stozac7014012014-02-14 15:03:43 -08003547void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3548 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003549{
Robert Carr2047fae2016-11-28 14:09:09 -08003550 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003551 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003552 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003553}
3554
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003555void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003556 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003557{
3558 String8 name;
3559 if (index < args.size()) {
3560 name = String8(args[index]);
3561 index++;
3562 }
3563
Dan Stoza9e56aa02015-11-02 13:00:03 -08003564 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3565 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003566 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003567
3568 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003569 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003570 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003571 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003572 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003573 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003574 }
Robert Carr2047fae2016-11-28 14:09:09 -08003575 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003576 }
3577}
3578
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003579void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003580 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003581{
3582 String8 name;
3583 if (index < args.size()) {
3584 name = String8(args[index]);
3585 index++;
3586 }
3587
Robert Carr2047fae2016-11-28 14:09:09 -08003588 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003589 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003590 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003591 }
Robert Carr2047fae2016-11-28 14:09:09 -08003592 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003593
Svetoslavd85084b2014-03-20 10:28:31 -07003594 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003595}
3596
Jamie Gennis6547ff42013-07-16 20:12:42 -07003597// This should only be called from the main thread. Otherwise it would need
3598// the lock and should use mCurrentState rather than mDrawingState.
3599void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003600 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003601 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003602 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003603
3604 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3605}
3606
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003607void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003608{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003609 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003610 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3611
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003612 if (isLayerTripleBufferingDisabled())
3613 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003614
3615 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003616 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003617 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003618 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003619 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3620 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003621 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003622}
3623
Dan Stozab90cf072015-03-05 11:05:59 -08003624void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3625{
3626 result.appendFormat("Static screen stats:\n");
3627 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3628 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3629 float percent = 100.0f *
3630 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3631 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3632 b + 1, bucketTimeSec, percent);
3633 }
3634 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3635 float percent = 100.0f *
3636 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3637 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3638 NUM_BUCKETS - 1, bucketTimeSec, percent);
3639}
3640
Dan Stozae77c7662016-05-13 11:37:28 -07003641void SurfaceFlinger::recordBufferingStats(const char* layerName,
3642 std::vector<OccupancyTracker::Segment>&& history) {
3643 Mutex::Autolock lock(mBufferingStatsMutex);
3644 auto& stats = mBufferingStats[layerName];
3645 for (const auto& segment : history) {
3646 if (!segment.usedThirdBuffer) {
3647 stats.twoBufferTime += segment.totalTime;
3648 }
3649 if (segment.occupancyAverage < 1.0f) {
3650 stats.doubleBufferedTime += segment.totalTime;
3651 } else if (segment.occupancyAverage < 2.0f) {
3652 stats.tripleBufferedTime += segment.totalTime;
3653 }
3654 ++stats.numSegments;
3655 stats.totalTime += segment.totalTime;
3656 }
3657}
3658
Brian Andersond6927fb2016-07-23 23:37:30 -07003659void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3660 result.appendFormat("Layer frame timestamps:\n");
3661
3662 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3663 const size_t count = currentLayers.size();
3664 for (size_t i=0 ; i<count ; i++) {
3665 currentLayers[i]->dumpFrameEvents(result);
3666 }
3667}
3668
Dan Stozae77c7662016-05-13 11:37:28 -07003669void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3670 result.append("Buffering stats:\n");
3671 result.append(" [Layer name] <Active time> <Two buffer> "
3672 "<Double buffered> <Triple buffered>\n");
3673 Mutex::Autolock lock(mBufferingStatsMutex);
3674 typedef std::tuple<std::string, float, float, float> BufferTuple;
3675 std::map<float, BufferTuple, std::greater<float>> sorted;
3676 for (const auto& statsPair : mBufferingStats) {
3677 const char* name = statsPair.first.c_str();
3678 const BufferingStats& stats = statsPair.second;
3679 if (stats.numSegments == 0) {
3680 continue;
3681 }
3682 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3683 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3684 stats.totalTime;
3685 float doubleBufferRatio = static_cast<float>(
3686 stats.doubleBufferedTime) / stats.totalTime;
3687 float tripleBufferRatio = static_cast<float>(
3688 stats.tripleBufferedTime) / stats.totalTime;
3689 sorted.insert({activeTime, {name, twoBufferRatio,
3690 doubleBufferRatio, tripleBufferRatio}});
3691 }
3692 for (const auto& sortedPair : sorted) {
3693 float activeTime = sortedPair.first;
3694 const BufferTuple& values = sortedPair.second;
3695 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3696 std::get<0>(values).c_str(), activeTime,
3697 std::get<1>(values), std::get<2>(values),
3698 std::get<3>(values));
3699 }
3700 result.append("\n");
3701}
3702
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003703void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3704 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003705 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003706
3707 // TODO: print out if wide-color mode is active or not
3708
3709 for (size_t d = 0; d < mDisplays.size(); d++) {
3710 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3711 int32_t hwcId = displayDevice->getHwcDisplayId();
3712 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3713 continue;
3714 }
3715
3716 result.appendFormat("Display %d color modes:\n", hwcId);
3717 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3718 for (auto&& mode : modes) {
3719 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3720 }
3721
3722 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3723 result.appendFormat(" Current color mode: %s (%d)\n",
3724 decodeColorMode(currentMode).c_str(), currentMode);
3725 }
3726 result.append("\n");
3727}
3728
Mathias Agopian74d211a2013-04-22 16:55:35 +02003729void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3730 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003731{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003732 bool colorize = false;
3733 if (index < args.size()
3734 && (args[index] == String16("--color"))) {
3735 colorize = true;
3736 index++;
3737 }
3738
3739 Colorizer colorizer(colorize);
3740
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003741 // figure out if we're stuck somewhere
3742 const nsecs_t now = systemTime();
3743 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3744 const nsecs_t inTransaction(mDebugInTransaction);
3745 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3746 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3747
3748 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003749 * Dump library configuration.
3750 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003751
3752 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003753 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003754 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003755 appendSfConfigString(result);
3756 appendUiConfigString(result);
3757 appendGuiConfigString(result);
3758 result.append("\n");
3759
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003760 result.append("\nWide-Color information:\n");
3761 dumpWideColorInfo(result);
3762
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003763 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003764 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003765 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003766 result.append(SyncFeatures::getInstance().toString());
3767 result.append("\n");
3768
Dan Stoza9e56aa02015-11-02 13:00:03 -08003769 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3770
Andy McFadden41d67d72014-04-25 16:58:34 -07003771 colorizer.bold(result);
3772 result.append("DispSync configuration: ");
3773 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003774 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003775 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003776 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003777 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003778 result.append("\n");
3779
Dan Stozab90cf072015-03-05 11:05:59 -08003780 // Dump static screen stats
3781 result.append("\n");
3782 dumpStaticScreenStats(result);
3783 result.append("\n");
3784
Dan Stozae77c7662016-05-13 11:37:28 -07003785 dumpBufferingStats(result);
3786
Andy McFadden4803b742012-09-24 19:07:20 -07003787 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003788 * Dump the visible layer list
3789 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003790 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003791 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003792 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003793 mCurrentState.traverseInZOrder([&](Layer* layer) {
Kalle Raitaa099a242017-01-11 11:17:29 -08003794 result.append(to_string(layer->getLayerDebugInfo()).c_str());
Robert Carr2047fae2016-11-28 14:09:09 -08003795 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003796
3797 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003798 * Dump Display state
3799 */
3800
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003801 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003802 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003803 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003804 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3805 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003806 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003807 }
3808
3809 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003810 * Dump SurfaceFlinger global state
3811 */
3812
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003813 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003814 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003815 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003816
Mathias Agopian888c8222012-08-04 21:10:38 -07003817 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003818 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003819
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003820 colorizer.bold(result);
3821 result.appendFormat("EGL implementation : %s\n",
3822 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3823 colorizer.reset(result);
3824 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003825 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003826
Mathias Agopian875d8e12013-06-07 15:35:48 -07003827 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003828
Mathias Agopian42977342012-08-05 00:40:46 -07003829 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003830 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3831 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003832 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003833 " last eglSwapBuffers() time: %f us\n"
3834 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003835 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003836 " refresh-rate : %f fps\n"
3837 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003838 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003839 " gpu_to_cpu_unsupported : %d\n"
3840 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003841 mLastSwapBufferTime/1000.0,
3842 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003843 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003844 1e9 / activeConfig->getVsyncPeriod(),
3845 activeConfig->getDpiX(),
3846 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003847 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003848
Mathias Agopian74d211a2013-04-22 16:55:35 +02003849 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003850 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003851
Mathias Agopian74d211a2013-04-22 16:55:35 +02003852 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003853 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003854
3855 /*
3856 * VSYNC state
3857 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003858 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003859 result.append("\n");
3860
3861 /*
3862 * HWC layer minidump
3863 */
3864 for (size_t d = 0; d < mDisplays.size(); d++) {
3865 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3866 int32_t hwcId = displayDevice->getHwcDisplayId();
3867 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3868 continue;
3869 }
3870
3871 result.appendFormat("Display %d HWC layers:\n", hwcId);
3872 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003873 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003874 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003875 });
Dan Stozae22aec72016-08-01 13:20:59 -07003876 result.append("\n");
3877 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003878
3879 /*
3880 * Dump HWComposer state
3881 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003882 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003883 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003884 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003885 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003886 result.appendFormat(" h/w composer %s\n",
3887 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003888 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003889
3890 /*
3891 * Dump gralloc state
3892 */
3893 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3894 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003895
3896 /*
3897 * Dump VrFlinger state if in use.
3898 */
3899 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3900 result.append("VrFlinger state:\n");
3901 result.append(mVrFlinger->Dump().c_str());
3902 result.append("\n");
3903 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003904}
3905
Mathias Agopian13127d82013-03-05 17:47:11 -08003906const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003907SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003908 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003909 wp<IBinder> dpy;
3910 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3911 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3912 dpy = mDisplays.keyAt(i);
3913 break;
3914 }
3915 }
3916 if (dpy == NULL) {
3917 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3918 // Just use the primary display so we have something to return
3919 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3920 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003921 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003922}
3923
Keun young Park63f165f2012-08-31 10:53:36 -07003924bool SurfaceFlinger::startDdmConnection()
3925{
3926 void* libddmconnection_dso =
3927 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3928 if (!libddmconnection_dso) {
3929 return false;
3930 }
3931 void (*DdmConnection_start)(const char* name);
3932 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003933 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003934 if (!DdmConnection_start) {
3935 dlclose(libddmconnection_dso);
3936 return false;
3937 }
3938 (*DdmConnection_start)(getServiceName());
3939 return true;
3940}
3941
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003942status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003943 switch (code) {
3944 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003945 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003946 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003947 case CLEAR_ANIMATION_FRAME_STATS:
3948 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003949 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003950 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003951 {
3952 // codes that require permission check
3953 IPCThreadState* ipc = IPCThreadState::self();
3954 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003955 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003956 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003957 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003958 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003959 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003960 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003961 break;
3962 }
Robert Carr1db73f62016-12-21 12:58:51 -08003963 /*
3964 * Calling setTransactionState is safe, because you need to have been
3965 * granted a reference to Client* and Handle* to do anything with it.
3966 *
3967 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3968 */
3969 case SET_TRANSACTION_STATE:
3970 case CREATE_SCOPED_CONNECTION:
3971 {
3972 return OK;
3973 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003974 case CAPTURE_SCREEN:
3975 {
3976 // codes that require permission check
3977 IPCThreadState* ipc = IPCThreadState::self();
3978 const int pid = ipc->getCallingPid();
3979 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003980 if ((uid != AID_GRAPHICS) &&
3981 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003982 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003983 return PERMISSION_DENIED;
3984 }
3985 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003986 }
3987 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003988 return OK;
3989}
3990
3991status_t SurfaceFlinger::onTransact(
3992 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3993{
3994 status_t credentialCheck = CheckTransactCodeCredentials(code);
3995 if (credentialCheck != OK) {
3996 return credentialCheck;
3997 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003998
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003999 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4000 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004001 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004002 IPCThreadState* ipc = IPCThreadState::self();
4003 const int uid = ipc->getCallingUid();
4004 if (CC_UNLIKELY(uid != AID_SYSTEM
4005 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004006 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004007 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004008 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004009 return PERMISSION_DENIED;
4010 }
4011 int n;
4012 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004013 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004014 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004015 return NO_ERROR;
4016 case 1002: // SHOW_UPDATES
4017 n = data.readInt32();
4018 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004019 invalidateHwcGeometry();
4020 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004021 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004022 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004023 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004024 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004025 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004026 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004027 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004028 setTransactionFlags(
4029 eTransactionNeeded|
4030 eDisplayTransactionNeeded|
4031 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004032 return NO_ERROR;
4033 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004034 case 1006:{ // send empty update
4035 signalRefresh();
4036 return NO_ERROR;
4037 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004038 case 1008: // toggle use of hw composer
4039 n = data.readInt32();
4040 mDebugDisableHWC = n ? 1 : 0;
4041 invalidateHwcGeometry();
4042 repaintEverything();
4043 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004044 case 1009: // toggle use of transform hint
4045 n = data.readInt32();
4046 mDebugDisableTransformHint = n ? 1 : 0;
4047 invalidateHwcGeometry();
4048 repaintEverything();
4049 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004050 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004051 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004052 reply->writeInt32(0);
4053 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004054 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004055 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004056 return NO_ERROR;
4057 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004058 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004059 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004060 return NO_ERROR;
4061 }
4062 case 1014: {
4063 // daltonize
4064 n = data.readInt32();
4065 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004066 case 1:
4067 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4068 break;
4069 case 2:
4070 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4071 break;
4072 case 3:
4073 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4074 break;
4075 default:
4076 mDaltonizer.setType(ColorBlindnessType::None);
4077 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004078 }
4079 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004080 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004081 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004082 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004083 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004084 invalidateHwcGeometry();
4085 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004086 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004087 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004088 case 1015: {
4089 // apply a color matrix
4090 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004091 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004092 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004093 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004094 for (size_t j = 0; j < 4; j++) {
4095 mColorMatrix[i][j] = data.readFloat();
4096 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004097 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004098 } else {
4099 mColorMatrix = mat4();
4100 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004101
4102 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4103 // the division by w in the fragment shader
4104 float4 lastRow(transpose(mColorMatrix)[3]);
4105 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4106 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4107 }
4108
Alan Viverette9c5a3332013-09-12 20:04:35 -07004109 invalidateHwcGeometry();
4110 repaintEverything();
4111 return NO_ERROR;
4112 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004113 // This is an experimental interface
4114 // Needs to be shifted to proper binder interface when we productize
4115 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004116 n = data.readInt32();
4117 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004118 return NO_ERROR;
4119 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004120 case 1017: {
4121 n = data.readInt32();
4122 mForceFullDamage = static_cast<bool>(n);
4123 return NO_ERROR;
4124 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004125 case 1018: { // Modify Choreographer's phase offset
4126 n = data.readInt32();
4127 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4128 return NO_ERROR;
4129 }
4130 case 1019: { // Modify SurfaceFlinger's phase offset
4131 n = data.readInt32();
4132 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4133 return NO_ERROR;
4134 }
Irvel468051e2016-06-13 16:44:44 -07004135 case 1020: { // Layer updates interceptor
4136 n = data.readInt32();
4137 if (n) {
4138 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004139 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004140 }
4141 else{
4142 ALOGV("Interceptor disabled");
4143 mInterceptor.disable();
4144 }
4145 return NO_ERROR;
4146 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004147 case 1021: { // Disable HWC virtual displays
4148 n = data.readInt32();
4149 mUseHwcVirtualDisplays = !n;
4150 return NO_ERROR;
4151 }
Romain Guy0147a172017-06-01 13:53:56 -07004152 case 1022: { // Set saturation boost
4153 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4154
4155 invalidateHwcGeometry();
4156 repaintEverything();
4157 return NO_ERROR;
4158 }
Romain Guy54f154a2017-10-24 21:40:32 +01004159 case 1023: { // Set native mode
4160 mForceNativeColorMode = data.readInt32() == 1;
4161
4162 invalidateHwcGeometry();
4163 repaintEverything();
4164 return NO_ERROR;
4165 }
4166 case 1024: { // Is wide color gamut rendering/color management supported?
4167 reply->writeBool(hasWideColorDisplay);
4168 return NO_ERROR;
4169 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004170 }
4171 }
4172 return err;
4173}
4174
Steven Thomas6d8110b2017-08-31 18:24:21 -07004175void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004176 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004177 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004178}
4179
Steven Thomas6d8110b2017-08-31 18:24:21 -07004180void SurfaceFlinger::repaintEverything() {
4181 ConditionalLock _l(mStateLock,
4182 std::this_thread::get_id() != mMainThreadId);
4183 repaintEverythingLocked();
4184}
4185
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004186// Checks that the requested width and height are valid and updates them to the display dimensions
4187// if they are set to 0
4188static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4189 Transform::orientation_flags rotation,
4190 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4191 // get screen geometry
4192 uint32_t displayWidth = displayDevice->getWidth();
4193 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004194
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004195 if (rotation & Transform::ROT_90) {
4196 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004197 }
4198
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004199 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4200 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4201 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4202 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004203 }
4204
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004205 if (*requestedWidth == 0) {
4206 *requestedWidth = displayWidth;
4207 }
4208 if (*requestedHeight == 0) {
4209 *requestedHeight = displayHeight;
4210 }
4211
4212 return NO_ERROR;
4213}
4214
4215// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4216class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004217public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004218 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4219 ~WindowDisconnector() {
4220 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004221 }
4222
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004223private:
4224 ANativeWindow* mWindow;
4225 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004226};
4227
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004228static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4229 uint32_t requestedHeight, bool hasWideColorDisplay,
4230 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4231 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4232 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4233
4234 int err = 0;
4235 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4236 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4237 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4238 err |= native_window_set_usage(window, usage);
4239
4240 if (hasWideColorDisplay) {
4241 err |= native_window_set_buffers_data_space(window,
4242 renderEngineUsesWideColor
4243 ? HAL_DATASPACE_DISPLAY_P3
4244 : HAL_DATASPACE_V0_SRGB);
4245 }
4246
4247 if (err != NO_ERROR) {
4248 return BAD_VALUE;
4249 }
4250
4251 /* TODO: Once we have the sync framework everywhere this can use
4252 * server-side waits on the fence that dequeueBuffer returns.
4253 */
4254 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4255 if (err != NO_ERROR) {
4256 return err;
4257 }
4258
4259 return NO_ERROR;
4260}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004261
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004262status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4263 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004264 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004265 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004266 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004267 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004268
4269 if (CC_UNLIKELY(display == 0))
4270 return BAD_VALUE;
4271
4272 if (CC_UNLIKELY(producer == 0))
4273 return BAD_VALUE;
4274
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004275 // if we have secure windows on this display, never allow the screen capture
4276 // unless the producer interface is local (i.e.: we can take a screenshot for
4277 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004278 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004279
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004280 // Convert to surfaceflinger's internal rotation type.
4281 Transform::orientation_flags rotationFlags;
4282 switch (rotation) {
4283 case ISurfaceComposer::eRotateNone:
4284 rotationFlags = Transform::ROT_0;
4285 break;
4286 case ISurfaceComposer::eRotate90:
4287 rotationFlags = Transform::ROT_90;
4288 break;
4289 case ISurfaceComposer::eRotate180:
4290 rotationFlags = Transform::ROT_180;
4291 break;
4292 case ISurfaceComposer::eRotate270:
4293 rotationFlags = Transform::ROT_270;
4294 break;
4295 default:
4296 rotationFlags = Transform::ROT_0;
4297 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4298 break;
4299 }
4300
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004301 { // Autolock scope
4302 Mutex::Autolock lock(mStateLock);
4303 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4304 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004305 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004306
4307 // create a surface (because we're a producer, and we need to
4308 // dequeue/queue a buffer)
4309 sp<Surface> surface = new Surface(producer, false);
4310
4311 // Put the screenshot Surface into async mode so that
4312 // Layer::headFenceHasSignaled will always return true and we'll latch the
4313 // first buffer regardless of whether or not its acquire fence has
4314 // signaled. This is needed to avoid a race condition in the rotation
4315 // animation. See b/30209608
4316 surface->setAsyncMode(true);
4317
4318 ANativeWindow* window = surface.get();
4319
4320 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4321 if (result != NO_ERROR) {
4322 return result;
4323 }
4324 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4325
4326 ANativeWindowBuffer* buffer = nullptr;
Romain Guy54f154a2017-10-24 21:40:32 +01004327 result = getWindowBuffer(window, reqWidth, reqHeight,
4328 hasWideColorDisplay && !mForceNativeColorMode,
4329 getRenderEngine().usesWideColor(), &buffer);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004330 if (result != NO_ERROR) {
4331 return result;
4332 }
4333
4334 // This mutex protects syncFd and captureResult for communication of the return values from the
4335 // main thread back to this Binder thread
4336 std::mutex captureMutex;
4337 std::condition_variable captureCondition;
4338 std::unique_lock<std::mutex> captureLock(captureMutex);
4339 int syncFd = -1;
4340 std::optional<status_t> captureResult;
4341
4342 sp<LambdaMessage> message = new LambdaMessage([&]() {
4343 // If there is a refresh pending, bug out early and tell the binder thread to try again
4344 // after the refresh.
4345 if (mRefreshPending) {
4346 ATRACE_NAME("Skipping screenshot for now");
4347 std::unique_lock<std::mutex> captureLock(captureMutex);
4348 captureResult = std::make_optional<status_t>(EAGAIN);
4349 captureCondition.notify_one();
4350 return;
4351 }
4352
4353 status_t result = NO_ERROR;
4354 int fd = -1;
4355 {
4356 Mutex::Autolock _l(mStateLock);
4357 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4358 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4359 minLayerZ, maxLayerZ, useIdentityTransform,
4360 rotationFlags, isLocalScreenshot, &fd);
4361 }
4362
4363 {
4364 std::unique_lock<std::mutex> captureLock(captureMutex);
4365 syncFd = fd;
4366 captureResult = std::make_optional<status_t>(result);
4367 captureCondition.notify_one();
4368 }
4369 });
4370
4371 result = postMessageAsync(message);
4372 if (result == NO_ERROR) {
4373 captureCondition.wait(captureLock, [&]() { return captureResult; });
4374 while (*captureResult == EAGAIN) {
4375 captureResult.reset();
4376 result = postMessageAsync(message);
4377 if (result != NO_ERROR) {
4378 return result;
4379 }
4380 captureCondition.wait(captureLock, [&]() { return captureResult; });
4381 }
4382 result = *captureResult;
4383 }
4384
4385 if (result == NO_ERROR) {
4386 // queueBuffer takes ownership of syncFd
4387 result = window->queueBuffer(window, buffer, syncFd);
4388 }
4389
4390 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004391}
4392
Mathias Agopian180f10d2013-04-10 22:55:41 -07004393
4394void SurfaceFlinger::renderScreenImplLocked(
4395 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004396 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004397 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004398 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004399{
4400 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004401 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004402
4403 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004404 const int32_t hw_w = hw->getWidth();
4405 const int32_t hw_h = hw->getHeight();
4406 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004407 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004408
Dan Stozac1879002014-05-22 15:59:05 -07004409 // if a default or invalid sourceCrop is passed in, set reasonable values
4410 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4411 !sourceCrop.isValid()) {
4412 sourceCrop.setLeftTop(Point(0, 0));
4413 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4414 }
4415
4416 // ensure that sourceCrop is inside screen
4417 if (sourceCrop.left < 0) {
4418 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4419 }
Dan Stozabe31f442014-06-11 11:20:54 -07004420 if (sourceCrop.right > hw_w) {
4421 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004422 }
4423 if (sourceCrop.top < 0) {
4424 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4425 }
Dan Stozabe31f442014-06-11 11:20:54 -07004426 if (sourceCrop.bottom > hw_h) {
4427 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004428 }
4429
Romain Guy88d37dd2017-05-26 17:57:05 -07004430#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01004431 engine.setWideColor(hw->getWideColorSupport() && !mForceNativeColorMode);
4432 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE : hw->getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004433#endif
4434
Mathias Agopian180f10d2013-04-10 22:55:41 -07004435 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004436 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004437
4438 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004439 engine.setViewportAndProjection(
4440 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004441 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004442
4443 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004444 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004445
Robert Carr1f0a16a2016-10-24 16:27:39 -07004446 // We loop through the first level of layers without traversing,
4447 // as we need to interpret min/max layer Z in the top level Z space.
4448 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004449 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004450 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004451 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004452 const Layer::State& state(layer->getDrawingState());
4453 if (state.z < minLayerZ || state.z > maxLayerZ) {
4454 continue;
4455 }
Dan Stoza412903f2017-04-27 13:42:17 -07004456 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004457 if (!layer->isVisible()) {
4458 return;
4459 }
4460 if (filtering) layer->setFiltering(true);
4461 layer->draw(hw, useIdentityTransform);
4462 if (filtering) layer->setFiltering(false);
4463 });
4464 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004465
Mathias Agopian931bda12013-08-28 18:11:46 -07004466 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004467}
4468
Dan Stozaabcda352017-06-01 14:37:39 -07004469// A simple RAII class that holds an EGLImage and destroys it either:
4470// a) When the destroy() method is called
4471// b) When the object goes out of scope
4472class ImageHolder {
4473public:
4474 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4475 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004476
Dan Stozaabcda352017-06-01 14:37:39 -07004477 void destroy() {
4478 if (mImage != EGL_NO_IMAGE_KHR) {
4479 eglDestroyImageKHR(mDisplay, mImage);
4480 mImage = EGL_NO_IMAGE_KHR;
4481 }
4482 }
4483
4484private:
4485 const EGLDisplay mDisplay;
4486 EGLImageKHR mImage;
4487};
4488
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004489status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4490 ANativeWindowBuffer* buffer, Rect sourceCrop,
4491 uint32_t reqWidth, uint32_t reqHeight,
4492 int32_t minLayerZ, int32_t maxLayerZ,
4493 bool useIdentityTransform,
4494 Transform::orientation_flags rotation,
4495 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004496 ATRACE_CALL();
4497
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004498 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004499 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004500 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004501 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004502 (state.z < minLayerZ || state.z > maxLayerZ)) {
4503 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004504 }
Dan Stoza412903f2017-04-27 13:42:17 -07004505 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004506 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4507 layer->isSecure());
4508 });
4509 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004510
4511 if (!isLocalScreenshot && secureLayerIsVisible) {
4512 ALOGW("FB is protected: PERMISSION_DENIED");
4513 return PERMISSION_DENIED;
4514 }
4515
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004516 int syncFd = -1;
4517 // create an EGLImage from the buffer so we can later
4518 // turn it into a texture
4519 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4520 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4521 if (image == EGL_NO_IMAGE_KHR) {
4522 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004523 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004524
Dan Stozaabcda352017-06-01 14:37:39 -07004525 // This will automatically destroy the image if we return before calling its destroy method
4526 ImageHolder imageHolder(mEGLDisplay, image);
4527
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004528 // this binds the given EGLImage as a framebuffer for the
4529 // duration of this scope.
4530 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004531 if (imageBond.getStatus() != NO_ERROR) {
4532 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004533 return INVALID_OPERATION;
4534 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004535
Dan Stozaabcda352017-06-01 14:37:39 -07004536 // this will in fact render into our dequeued buffer
4537 // via an FBO, which means we didn't have to create
4538 // an EGLSurface and therefore we're not
4539 // dependent on the context's EGLConfig.
4540 renderScreenImplLocked(
4541 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4542 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004543
Dan Stozaabcda352017-06-01 14:37:39 -07004544 // Attempt to create a sync khr object that can produce a sync point. If that
4545 // isn't available, create a non-dupable sync object in the fallback path and
4546 // wait on it directly.
4547 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4548 if (!DEBUG_SCREENSHOTS) {
4549 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4550 // native fence fd will not be populated until flush() is done.
4551 getRenderEngine().flush();
4552 }
4553
4554 if (sync != EGL_NO_SYNC_KHR) {
4555 // get the sync fd
4556 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4557 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4558 ALOGW("captureScreen: failed to dup sync khr object");
4559 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004560 }
Dan Stozaabcda352017-06-01 14:37:39 -07004561 eglDestroySyncKHR(mEGLDisplay, sync);
4562 } else {
4563 // fallback path
4564 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004565 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004566 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4567 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4568 EGLint eglErr = eglGetError();
4569 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4570 ALOGW("captureScreen: fence wait timed out");
4571 } else {
4572 ALOGW_IF(eglErr != EGL_SUCCESS,
4573 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004574 }
4575 eglDestroySyncKHR(mEGLDisplay, sync);
4576 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004577 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004578 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004579 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004580 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004581
4582 if (DEBUG_SCREENSHOTS) {
4583 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4584 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4585 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4586 hw, minLayerZ, maxLayerZ);
4587 delete [] pixels;
4588 }
4589
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004590 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004591 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004592
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004593 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004594}
4595
Mathias Agopiand5556842013-09-19 17:08:37 -07004596void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004597 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004598 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004599 for (size_t y=0 ; y<h ; y++) {
4600 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4601 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004602 if (p[x] != 0xFF000000) return;
4603 }
4604 }
4605 ALOGE("*** we just took a black screenshot ***\n"
4606 "requested minz=%d, maxz=%d, layerStack=%d",
4607 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004608
Robert Carr2047fae2016-11-28 14:09:09 -08004609 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004610 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004611 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004612 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004613 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004614 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004615 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4616 layer->isVisible() ? '+' : '-',
4617 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004618 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004619 i++;
4620 });
4621 }
4622 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004623 }
4624}
4625
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004626// ---------------------------------------------------------------------------
4627
Dan Stoza412903f2017-04-27 13:42:17 -07004628void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4629 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004630}
4631
Dan Stoza412903f2017-04-27 13:42:17 -07004632void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4633 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004634}
4635
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004636}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004637
4638
4639#if defined(__gl_h_)
4640#error "don't include gl/gl.h in this file"
4641#endif
4642
4643#if defined(__gl2_h_)
4644#error "don't include gl2/gl2.h in this file"
4645#endif