blob: 54c040dae9dbaf1c9e41cdad4be813c660711298 [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"
chaviw13fdc492017-06-27 12:40:18 -070076#include "ColorLayer.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
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
Jiyong Park00b15b82017-08-10 20:30:56 +0900103extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
Mathias Agopianca088332013-03-28 17:44:13 -0700104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700106
Jaesoo Lee43518572017-01-23 19:03:16 +0900107using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108using namespace android::hardware::configstore::V1_0;
109
Steven Thomasb02664d2017-07-26 18:48:28 -0700110namespace {
111class ConditionalLock {
112public:
113 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
114 if (lock) {
115 mMutex.lock();
116 }
117 }
118 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
119private:
120 Mutex& mMutex;
121 bool mLocked;
122};
123} // namespace anonymous
124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125// ---------------------------------------------------------------------------
126
Mathias Agopian99b49842011-06-27 16:05:52 -0700127const String16 sHardwareTest("android.permission.HARDWARE_TEST");
128const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
129const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
130const String16 sDump("android.permission.DUMP");
131
132// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800133int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
134int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700135bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700136int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700137bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800138uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800139bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800140bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800141int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600142bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700143
Kalle Raitaa099a242017-01-11 11:17:29 -0800144
145std::string getHwcServiceName() {
146 char value[PROPERTY_VALUE_MAX] = {};
147 property_get("debug.sf.hwc_service_name", value, "default");
148 ALOGI("Using HWComposer service: '%s'", value);
149 return std::string(value);
150}
151
152bool useTrebleTestingOverride() {
153 char value[PROPERTY_VALUE_MAX] = {};
154 property_get("debug.sf.treble_testing_override", value, "false");
155 ALOGI("Treble testing override: '%s'", value);
156 return std::string(value) == "true";
157}
158
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700160 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700162 mTransactionPending(false),
163 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700164 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700165 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700166 mRepaintEverything(0),
Kalle Raitaa099a242017-01-11 11:17:29 -0800167 mHwcServiceName(getHwcServiceName()),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800168 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800170 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800171 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800172 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800173 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700175 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700176 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700177 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700178 mDebugInSwapBuffers(0),
179 mLastSwapBufferTime(0),
180 mDebugInTransaction(0),
181 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700182 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700183 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800184 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000185 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700186 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700187 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700188 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800189 mHasPoweredOff(false),
190 mFrameBuckets(),
191 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700192 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800193 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700194 mVrFlingerRequestsDisplay(false),
195 mMainThreadId(std::this_thread::get_id()),
196 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800198 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800199
200 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
201 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
202
203 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
204 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
205
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800206 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700209 useContextPriority = getBool< ISurfaceFlingerConfigs,
210 &ISurfaceFlingerConfigs::useContextPriority>(false);
211
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700212 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
213 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
214
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700215 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
216 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
217
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800218 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
219 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
220
Steven Thomas050b2c82017-03-06 11:45:16 -0800221 // Vr flinger is only enabled on Daydream ready devices.
222 useVrFlinger = getBool< ISurfaceFlingerConfigs,
223 &ISurfaceFlingerConfigs::useVrFlinger>(false);
224
Fabien Sanglard1971b632017-03-10 14:50:03 -0800225 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
226 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
227
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600228 hasWideColorDisplay =
229 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
230
Saurabh Shahf4174532017-07-13 10:45:07 -0700231 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233 // debugging stuff...
234 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700235
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700237 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239 property_get("debug.sf.showupdates", value, "0");
240 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700241
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700242 property_get("debug.sf.ddms", value, "0");
243 mDebugDDMS = atoi(value);
244 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700245 if (!startDdmConnection()) {
246 // start failed, and DDMS debugging not enabled
247 mDebugDDMS = 0;
248 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700249 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700250 ALOGI_IF(mDebugRegion, "showupdates enabled");
251 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700252
253 property_get("debug.sf.disable_backpressure", value, "0");
254 mPropagateBackpressure = !atoi(value);
255 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700256
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800257 property_get("debug.sf.enable_hwc_vds", value, "0");
258 mUseHwcVirtualDisplays = atoi(value);
259 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800260
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800261 property_get("ro.sf.disable_triple_buffer", value, "1");
262 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800263 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700264
Romain Guy11d63f42017-07-20 12:47:14 -0700265 // We should be reading 'persist.sys.sf.color_saturation' here
266 // but since /data may be encrypted, we need to wait until after vold
267 // comes online to attempt to read the property. The property is
268 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800269
270 if (useTrebleTestingOverride()) {
271 // Without the override SurfaceFlinger cannot connect to HIDL
272 // services that are not listed in the manifests. Considered
273 // deriving the setting from the set service name, but it
274 // would be brittle if the name that's not 'default' is used
275 // for production purposes later on.
276 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
277 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800278}
279
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800280void SurfaceFlinger::onFirstRef()
281{
282 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800283}
284
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800285SurfaceFlinger::~SurfaceFlinger()
286{
Mathias Agopiana4912602012-07-12 14:25:33 -0700287 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
288 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
289 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290}
291
Dan Stozac7014012014-02-14 15:03:43 -0800292void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800293{
294 // the window manager died on us. prepare its eulogy.
295
Andy McFadden13a082e2012-08-24 10:16:42 -0700296 // restore initial conditions (default device unblank, etc)
297 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800298
299 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700300 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800301}
302
Robert Carr1db73f62016-12-21 12:58:51 -0800303static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700304 status_t err = client->initCheck();
305 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800306 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307 }
Robert Carr1db73f62016-12-21 12:58:51 -0800308 return nullptr;
309}
310
311sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
312 return initClient(new Client(this));
313}
314
315sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
316 const sp<IGraphicBufferProducer>& gbp) {
317 if (authenticateSurfaceTexture(gbp) == false) {
318 return nullptr;
319 }
320 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
321 if (layer == nullptr) {
322 return nullptr;
323 }
324
325 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326}
327
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700328sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
329 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700330{
331 class DisplayToken : public BBinder {
332 sp<SurfaceFlinger> flinger;
333 virtual ~DisplayToken() {
334 // no more references, this display must be terminated
335 Mutex::Autolock _l(flinger->mStateLock);
336 flinger->mCurrentState.displays.removeItem(this);
337 flinger->setTransactionFlags(eDisplayTransactionNeeded);
338 }
339 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700340 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700341 : flinger(flinger) {
342 }
343 };
344
345 sp<BBinder> token = new DisplayToken(this);
346
347 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700348 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700349 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700350 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700351 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700352 return token;
353}
354
Jesse Hall6c913be2013-08-08 12:15:49 -0700355void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
356 Mutex::Autolock _l(mStateLock);
357
358 ssize_t idx = mCurrentState.displays.indexOfKey(display);
359 if (idx < 0) {
360 ALOGW("destroyDisplay: invalid display token");
361 return;
362 }
363
364 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
365 if (!info.isVirtualDisplay()) {
366 ALOGE("destroyDisplay called for non-virtual display");
367 return;
368 }
Irvelffc9efc2016-07-27 15:16:37 -0700369 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700370 mCurrentState.displays.removeItemsAt(idx);
371 setTransactionFlags(eDisplayTransactionNeeded);
372}
373
Jesse Hall692c7232012-11-08 15:41:56 -0800374void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800375 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800376 ALOGW_IF(mBuiltinDisplays[type],
377 "Overwriting display token for display type %d", type);
378 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800379 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700380 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800381 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700382 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800383}
384
Mathias Agopiane57f2922012-08-09 16:29:12 -0700385sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700386 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700387 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
388 return NULL;
389 }
Jesse Hall692c7232012-11-08 15:41:56 -0800390 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700391}
392
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800393void SurfaceFlinger::bootFinished()
394{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700395 if (mStartPropertySetThread->join() != NO_ERROR) {
396 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800397 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398 const nsecs_t now = systemTime();
399 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000400 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700401
402 // wait patiently for the window manager death
403 const String16 name("window");
404 sp<IBinder> window(defaultServiceManager()->getService(name));
405 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700406 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700407 }
408
Steven Thomas050b2c82017-03-06 11:45:16 -0800409 if (mVrFlinger) {
410 mVrFlinger->OnBootFinished();
411 }
412
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700413 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700414 // formerly we would just kill the process, but we now ask it to exit so it
415 // can choose where to stop the animation.
416 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700417
418 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
419 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
420 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700421
Thierry Strudel2924d012017-08-14 15:19:37 -0700422 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700423 readPersistentProperties();
424 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700425 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426}
427
Mathias Agopian3f844832013-08-07 21:24:32 -0700428void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700429 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700430 RenderEngine& engine;
431 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700432 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700433 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
434 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700435 }
436 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700437 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700438 return true;
439 }
440 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700441 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700442}
443
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700444class DispSyncSource : public VSyncSource, private DispSync::Callback {
445public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700446 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000447 const char* name) :
448 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700449 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700450 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000451 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
452 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700453 mDispSync(dispSync),
454 mCallbackMutex(),
455 mCallback(),
456 mVsyncMutex(),
457 mPhaseOffset(phaseOffset),
458 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700459
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700460 virtual ~DispSyncSource() {}
461
462 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700463 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700464 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000465 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700466 static_cast<DispSync::Callback*>(this));
467 if (err != NO_ERROR) {
468 ALOGE("error registering vsync callback: %s (%d)",
469 strerror(-err), err);
470 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700471 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700472 } else {
473 status_t err = mDispSync->removeEventListener(
474 static_cast<DispSync::Callback*>(this));
475 if (err != NO_ERROR) {
476 ALOGE("error unregistering vsync callback: %s (%d)",
477 strerror(-err), err);
478 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700479 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700481 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700482 }
483
484 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700485 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700486 mCallback = callback;
487 }
488
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700489 virtual void setPhaseOffset(nsecs_t phaseOffset) {
490 Mutex::Autolock lock(mVsyncMutex);
491
492 // Normalize phaseOffset to [0, period)
493 auto period = mDispSync->getPeriod();
494 phaseOffset %= period;
495 if (phaseOffset < 0) {
496 // If we're here, then phaseOffset is in (-period, 0). After this
497 // operation, it will be in (0, period)
498 phaseOffset += period;
499 }
500 mPhaseOffset = phaseOffset;
501
502 // If we're not enabled, we don't need to mess with the listeners
503 if (!mEnabled) {
504 return;
505 }
506
507 // Remove the listener with the old offset
508 status_t err = mDispSync->removeEventListener(
509 static_cast<DispSync::Callback*>(this));
510 if (err != NO_ERROR) {
511 ALOGE("error unregistering vsync callback: %s (%d)",
512 strerror(-err), err);
513 }
514
515 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000516 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700517 static_cast<DispSync::Callback*>(this));
518 if (err != NO_ERROR) {
519 ALOGE("error registering vsync callback: %s (%d)",
520 strerror(-err), err);
521 }
522 }
523
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700524private:
525 virtual void onDispSyncEvent(nsecs_t when) {
526 sp<VSyncSource::Callback> callback;
527 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700528 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700529 callback = mCallback;
530
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700531 if (mTraceVsync) {
532 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700533 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700534 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700535 }
536
537 if (callback != NULL) {
538 callback->onVSyncEvent(when);
539 }
540 }
541
Tim Murray4a4e4a22016-04-19 16:29:23 +0000542 const char* const mName;
543
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544 int mValue;
545
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700546 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700547 const String8 mVsyncOnLabel;
548 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700549
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700550 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700551
552 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700553 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700554
555 Mutex mVsyncMutex; // Protects the following
556 nsecs_t mPhaseOffset;
557 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700558};
559
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700560class InjectVSyncSource : public VSyncSource {
561public:
562 InjectVSyncSource() {}
563
564 virtual ~InjectVSyncSource() {}
565
566 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
567 std::lock_guard<std::mutex> lock(mCallbackMutex);
568 mCallback = callback;
569 }
570
571 virtual void onInjectSyncEvent(nsecs_t when) {
572 std::lock_guard<std::mutex> lock(mCallbackMutex);
573 mCallback->onVSyncEvent(when);
574 }
575
576 virtual void setVSyncEnabled(bool) {}
577 virtual void setPhaseOffset(nsecs_t) {}
578
579private:
580 std::mutex mCallbackMutex; // Protects the following
581 sp<VSyncSource::Callback> mCallback;
582};
583
Wei Wangf9b05ee2017-07-19 20:59:39 -0700584// Do not call property_set on main thread which will be blocked by init
585// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700586void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700587 ALOGI( "SurfaceFlinger's main thread ready to run. "
588 "Initializing graphics H/W...");
589
Thierry Strudel2924d012017-08-14 15:19:37 -0700590 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900591
Steven Thomasb02664d2017-07-26 18:48:28 -0700592 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800593
Steven Thomasb02664d2017-07-26 18:48:28 -0700594 // initialize EGL for the default display
595 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
596 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800597
Steven Thomasb02664d2017-07-26 18:48:28 -0700598 // start the EventThread
599 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
600 vsyncPhaseOffsetNs, true, "app");
601 mEventThread = new EventThread(vsyncSrc, *this, false);
602 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
603 sfVsyncPhaseOffsetNs, true, "sf");
604 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
605 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800606
Steven Thomasb02664d2017-07-26 18:48:28 -0700607 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
608 struct sched_param param = {0};
609 param.sched_priority = 2;
610 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
611 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
612 }
613 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
614 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800615 }
616
Steven Thomasb02664d2017-07-26 18:48:28 -0700617 // Get a RenderEngine for the given display / config (can't fail)
618 mRenderEngine = RenderEngine::create(mEGLDisplay,
619 HAL_PIXEL_FORMAT_RGBA_8888,
620 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800621
Steven Thomasb02664d2017-07-26 18:48:28 -0700622 // retrieve the EGL context that was selected/created
623 mEGLContext = mRenderEngine->getEGLContext();
624
625 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
626 "couldn't create EGLContext");
627
628 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
629 "Starting with vr flinger active is not currently supported.");
630 mHwc.reset(new HWComposer(mHwcServiceName));
631 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800632
Steven Thomas050b2c82017-03-06 11:45:16 -0800633 if (useVrFlinger) {
634 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700635 // This callback is called from the vr flinger dispatch thread. We
636 // need to call signalTransaction(), which requires holding
637 // mStateLock when we're not on the main thread. Acquiring
638 // mStateLock from the vr flinger dispatch thread might trigger a
639 // deadlock in surface flinger (see b/66916578), so post a message
640 // to be handled on the main thread instead.
641 sp<LambdaMessage> message = new LambdaMessage([=]() {
642 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
643 mVrFlingerRequestsDisplay = requestDisplay;
644 signalTransaction();
645 });
646 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800647 };
648 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
649 vrFlingerRequestDisplayCallback);
650 if (!mVrFlinger) {
651 ALOGE("Failed to start vrflinger");
652 }
653 }
654
Jamie Gennisd1700752013-10-14 12:22:52 -0700655 mEventControlThread = new EventControlThread(this);
656 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
657
Mathias Agopian92a979a2012-08-02 18:32:23 -0700658 // initialize our drawing state
659 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700660
Andy McFadden13a082e2012-08-24 10:16:42 -0700661 // set initial conditions (e.g. unblank default device)
662 initializeDisplays();
663
Dan Stoza4e637772016-07-28 13:31:51 -0700664 mRenderEngine->primeCache();
665
Wei Wangf9b05ee2017-07-19 20:59:39 -0700666 // Inform native graphics APIs whether the present timestamp is supported:
667 if (getHwComposer().hasCapability(
668 HWC2::Capability::PresentFenceIsNotReliable)) {
669 mStartPropertySetThread = new StartPropertySetThread(false);
670 } else {
671 mStartPropertySetThread = new StartPropertySetThread(true);
672 }
673
674 if (mStartPropertySetThread->Start() != NO_ERROR) {
675 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800676 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800677
Dan Stoza9e56aa02015-11-02 13:00:03 -0800678 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700679}
680
Romain Guy11d63f42017-07-20 12:47:14 -0700681void SurfaceFlinger::readPersistentProperties() {
682 char value[PROPERTY_VALUE_MAX];
683
684 property_get("persist.sys.sf.color_saturation", value, "1.0");
685 mSaturation = atof(value);
686 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100687
688 property_get("persist.sys.sf.native_mode", value, "0");
689 mForceNativeColorMode = atoi(value) == 1;
690 if (mForceNativeColorMode) {
691 ALOGV("Forcing native color mode");
692 }
Romain Guy11d63f42017-07-20 12:47:14 -0700693}
694
Mathias Agopiana67e4182012-06-19 17:26:12 -0700695void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800696 // Start boot animation service by setting a property mailbox
697 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800699 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700700 if (mStartPropertySetThread->join() != NO_ERROR) {
701 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800702 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700703}
704
Mathias Agopian875d8e12013-06-07 15:35:48 -0700705size_t SurfaceFlinger::getMaxTextureSize() const {
706 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700707}
708
Mathias Agopian875d8e12013-06-07 15:35:48 -0700709size_t SurfaceFlinger::getMaxViewportDims() const {
710 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700711}
712
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800713// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800714
Jamie Gennis582270d2011-08-17 18:19:00 -0700715bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800716 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800717 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800718 return authenticateSurfaceTextureLocked(bufferProducer);
719}
720
721bool SurfaceFlinger::authenticateSurfaceTextureLocked(
722 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800723 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700724 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800725}
726
Brian Anderson6b376712017-04-04 10:51:39 -0700727status_t SurfaceFlinger::getSupportedFrameTimestamps(
728 std::vector<FrameEvent>* outSupported) const {
729 *outSupported = {
730 FrameEvent::REQUESTED_PRESENT,
731 FrameEvent::ACQUIRE,
732 FrameEvent::LATCH,
733 FrameEvent::FIRST_REFRESH_START,
734 FrameEvent::LAST_REFRESH_START,
735 FrameEvent::GPU_COMPOSITION_DONE,
736 FrameEvent::DEQUEUE_READY,
737 FrameEvent::RELEASE,
738 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700739 ConditionalLock _l(mStateLock,
740 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700741 if (!getHwComposer().hasCapability(
742 HWC2::Capability::PresentFenceIsNotReliable)) {
743 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
744 }
745 return NO_ERROR;
746}
747
Dan Stoza7f7da322014-05-02 15:26:25 -0700748status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
749 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700750 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700751 return BAD_VALUE;
752 }
753
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500754 if (!display.get())
755 return NAME_NOT_FOUND;
756
Jesse Hall692c7232012-11-08 15:41:56 -0800757 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700758 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800759 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700760 type = i;
761 break;
762 }
763 }
764
765 if (type < 0) {
766 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700767 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700768
Mathias Agopian8b736f12012-08-13 17:54:26 -0700769 // TODO: Not sure if display density should handled by SF any longer
770 class Density {
771 static int getDensityFromProperty(char const* propName) {
772 char property[PROPERTY_VALUE_MAX];
773 int density = 0;
774 if (property_get(propName, property, NULL) > 0) {
775 density = atoi(property);
776 }
777 return density;
778 }
779 public:
780 static int getEmuDensity() {
781 return getDensityFromProperty("qemu.sf.lcd_density"); }
782 static int getBuildDensity() {
783 return getDensityFromProperty("ro.sf.lcd_density"); }
784 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700785
Dan Stoza7f7da322014-05-02 15:26:25 -0700786 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700787
Steven Thomas6d8110b2017-08-31 18:24:21 -0700788 ConditionalLock _l(mStateLock,
789 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800790 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700791 DisplayInfo info = DisplayInfo();
792
Dan Stoza9e56aa02015-11-02 13:00:03 -0800793 float xdpi = hwConfig->getDpiX();
794 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700795
796 if (type == DisplayDevice::DISPLAY_PRIMARY) {
797 // The density of the device is provided by a build property
798 float density = Density::getBuildDensity() / 160.0f;
799 if (density == 0) {
800 // the build doesn't provide a density -- this is wrong!
801 // use xdpi instead
802 ALOGE("ro.sf.lcd_density must be defined as a build property");
803 density = xdpi / 160.0f;
804 }
805 if (Density::getEmuDensity()) {
806 // if "qemu.sf.lcd_density" is specified, it overrides everything
807 xdpi = ydpi = density = Density::getEmuDensity();
808 density /= 160.0f;
809 }
810 info.density = density;
811
812 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700813 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000814 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700815 } else {
816 // TODO: where should this value come from?
817 static const int TV_DENSITY = 213;
818 info.density = TV_DENSITY / 160.0f;
819 info.orientation = 0;
820 }
821
Dan Stoza9e56aa02015-11-02 13:00:03 -0800822 info.w = hwConfig->getWidth();
823 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 info.xdpi = xdpi;
825 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900827 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828
Andy McFadden91b2ca82014-06-13 14:04:23 -0700829 // This is how far in advance a buffer must be queued for
830 // presentation at a given time. If you want a buffer to appear
831 // on the screen at time N, you must submit the buffer before
832 // (N - presentationDeadline).
833 //
834 // Normally it's one full refresh period (to give SF a chance to
835 // latch the buffer), but this can be reduced by configuring a
836 // DispSync offset. Any additional delays introduced by the hardware
837 // composer or panel must be accounted for here.
838 //
839 // We add an additional 1ms to allow for processing time and
840 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800842 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700843
844 // All non-virtual displays are currently considered secure.
845 info.secure = true;
846
Michael Wright28f24d02016-07-12 13:30:53 -0700847 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700848 }
849
Dan Stoza7f7da322014-05-02 15:26:25 -0700850 return NO_ERROR;
851}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700852
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800853status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700854 DisplayStatInfo* stats) {
855 if (stats == NULL) {
856 return BAD_VALUE;
857 }
858
859 // FIXME for now we always return stats for the primary display
860 memset(stats, 0, sizeof(*stats));
861 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
862 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
863 return NO_ERROR;
864}
865
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700866int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800867 if (display == NULL) {
868 ALOGE("%s : display is NULL", __func__);
869 return BAD_VALUE;
870 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700871
872 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700873 if (device != NULL) {
874 return device->getActiveConfig();
875 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700876
Dan Stoza24a42e92015-03-09 10:04:11 -0700877 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700878}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700879
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700880void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
881 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
882 this);
883 int32_t type = hw->getDisplayType();
884 int currentMode = hw->getActiveConfig();
885
886 if (mode == currentMode) {
887 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
888 return;
889 }
890
891 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
892 ALOGW("Trying to set config for virtual display");
893 return;
894 }
895
896 hw->setActiveConfig(mode);
897 getHwComposer().setActiveConfig(type, mode);
898}
899
900status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
901 class MessageSetActiveConfig: public MessageBase {
902 SurfaceFlinger& mFlinger;
903 sp<IBinder> mDisplay;
904 int mMode;
905 public:
906 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
907 int mode) :
908 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
909 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700910 Vector<DisplayInfo> configs;
911 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700912 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700913 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700914 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700915 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700916 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700917 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
918 if (hw == NULL) {
919 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700920 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700921 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
922 ALOGW("Attempt to set active config = %d for virtual display",
923 mMode);
924 } else {
925 mFlinger.setActiveConfigInternal(hw, mMode);
926 }
927 return true;
928 }
929 };
930 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
931 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700932 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700933}
Michael Wright28f24d02016-07-12 13:30:53 -0700934status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
935 Vector<android_color_mode_t>* outColorModes) {
936 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
937 return BAD_VALUE;
938 }
939
940 if (!display.get()) {
941 return NAME_NOT_FOUND;
942 }
943
944 int32_t type = NAME_NOT_FOUND;
945 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
946 if (display == mBuiltinDisplays[i]) {
947 type = i;
948 break;
949 }
950 }
951
952 if (type < 0) {
953 return type;
954 }
955
Steven Thomas6d8110b2017-08-31 18:24:21 -0700956 std::vector<android_color_mode_t> modes;
957 {
958 ConditionalLock _l(mStateLock,
959 std::this_thread::get_id() != mMainThreadId);
960 modes = getHwComposer().getColorModes(type);
961 }
Michael Wright28f24d02016-07-12 13:30:53 -0700962 outColorModes->clear();
963 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
964
965 return NO_ERROR;
966}
967
968android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700969 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700970 if (device != nullptr) {
971 return device->getActiveColorMode();
972 }
973 return static_cast<android_color_mode_t>(BAD_VALUE);
974}
975
976void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
977 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700978 int32_t type = hw->getDisplayType();
979 android_color_mode_t currentMode = hw->getActiveColorMode();
980
981 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700982 return;
983 }
984
985 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
986 ALOGW("Trying to set config for virtual display");
987 return;
988 }
989
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600990 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
991 hw->getDisplayType());
992
Michael Wright28f24d02016-07-12 13:30:53 -0700993 hw->setActiveColorMode(mode);
994 getHwComposer().setActiveColorMode(type, mode);
995}
996
997
998status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
999 android_color_mode_t colorMode) {
1000 class MessageSetActiveColorMode: public MessageBase {
1001 SurfaceFlinger& mFlinger;
1002 sp<IBinder> mDisplay;
1003 android_color_mode_t mMode;
1004 public:
1005 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1006 android_color_mode_t mode) :
1007 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1008 virtual bool handler() {
1009 Vector<android_color_mode_t> modes;
1010 mFlinger.getDisplayColorModes(mDisplay, &modes);
1011 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1012 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001013 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1014 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001015 return true;
1016 }
1017 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1018 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001019 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1020 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001021 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001022 ALOGW("Attempt to set active color mode %s %d for virtual display",
1023 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001024 } else {
1025 mFlinger.setActiveColorModeInternal(hw, mMode);
1026 }
1027 return true;
1028 }
1029 };
1030 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1031 postMessageSync(msg);
1032 return NO_ERROR;
1033}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001034
Svetoslavd85084b2014-03-20 10:28:31 -07001035status_t SurfaceFlinger::clearAnimationFrameStats() {
1036 Mutex::Autolock _l(mStateLock);
1037 mAnimFrameTracker.clearStats();
1038 return NO_ERROR;
1039}
1040
1041status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1042 Mutex::Autolock _l(mStateLock);
1043 mAnimFrameTracker.getStats(outStats);
1044 return NO_ERROR;
1045}
1046
Dan Stozac4f471e2016-03-24 09:31:08 -07001047status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1048 HdrCapabilities* outCapabilities) const {
1049 Mutex::Autolock _l(mStateLock);
1050
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001051 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001052 if (displayDevice == nullptr) {
1053 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1054 return BAD_VALUE;
1055 }
1056
1057 std::unique_ptr<HdrCapabilities> capabilities =
1058 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1059 if (capabilities) {
1060 std::swap(*outCapabilities, *capabilities);
1061 } else {
1062 return BAD_VALUE;
1063 }
1064
1065 return NO_ERROR;
1066}
1067
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001068status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1069 if (enable == mInjectVSyncs) {
1070 return NO_ERROR;
1071 }
1072
1073 if (enable) {
1074 mInjectVSyncs = enable;
1075 ALOGV("VSync Injections enabled");
1076 if (mVSyncInjector.get() == nullptr) {
1077 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001078 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001079 }
1080 mEventQueue.setEventThread(mInjectorEventThread);
1081 } else {
1082 mInjectVSyncs = enable;
1083 ALOGV("VSync Injections disabled");
1084 mEventQueue.setEventThread(mSFEventThread);
1085 mVSyncInjector.clear();
1086 }
1087 return NO_ERROR;
1088}
1089
1090status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1091 if (!mInjectVSyncs) {
1092 ALOGE("VSync Injections not enabled");
1093 return BAD_VALUE;
1094 }
1095 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1096 ALOGV("Injecting VSync inside SurfaceFlinger");
1097 mVSyncInjector->onInjectSyncEvent(when);
1098 }
1099 return NO_ERROR;
1100}
1101
Kalle Raitaa099a242017-01-11 11:17:29 -08001102status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1103 IPCThreadState* ipc = IPCThreadState::self();
1104 const int pid = ipc->getCallingPid();
1105 const int uid = ipc->getCallingUid();
1106 if ((uid != AID_SHELL) &&
1107 !PermissionCache::checkPermission(sDump, pid, uid)) {
1108 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1109 return PERMISSION_DENIED;
1110 }
1111
1112 // Try to acquire a lock for 1s, fail gracefully
1113 const status_t err = mStateLock.timedLock(s2ns(1));
1114 const bool locked = (err == NO_ERROR);
1115 if (!locked) {
1116 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1117 return TIMED_OUT;
1118 }
1119
1120 outLayers->clear();
1121 mCurrentState.traverseInZOrder([&](Layer* layer) {
1122 outLayers->push_back(layer->getLayerDebugInfo());
1123 });
1124
1125 mStateLock.unlock();
1126 return NO_ERROR;
1127}
1128
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001129// ----------------------------------------------------------------------------
1130
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001131sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1132 ISurfaceComposer::VsyncSource vsyncSource) {
1133 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1134 return mSFEventThread->createEventConnection();
1135 } else {
1136 return mEventThread->createEventConnection();
1137 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001138}
1139
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001140// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001141
1142void SurfaceFlinger::waitForEvent() {
1143 mEventQueue.waitMessage();
1144}
1145
1146void SurfaceFlinger::signalTransaction() {
1147 mEventQueue.invalidate();
1148}
1149
1150void SurfaceFlinger::signalLayerUpdate() {
1151 mEventQueue.invalidate();
1152}
1153
1154void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001155 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001156 mEventQueue.refresh();
1157}
1158
1159status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001160 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001161 return mEventQueue.postMessage(msg, reltime);
1162}
1163
1164status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001165 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001166 status_t res = mEventQueue.postMessage(msg, reltime);
1167 if (res == NO_ERROR) {
1168 msg->wait();
1169 }
1170 return res;
1171}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001172
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001173void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001174 do {
1175 waitForEvent();
1176 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001177}
1178
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001179void SurfaceFlinger::enableHardwareVsync() {
1180 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001181 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001182 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001183 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1184 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001185 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001186 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187}
1188
Jesse Hall948fe0c2013-10-14 12:56:09 -07001189void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001190 Mutex::Autolock _l(mHWVsyncLock);
1191
Jesse Hall948fe0c2013-10-14 12:56:09 -07001192 if (makeAvailable) {
1193 mHWVsyncAvailable = true;
1194 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001195 // Hardware vsync is not currently available, so abort the resync
1196 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001197 return;
1198 }
1199
Dan Stoza9e56aa02015-11-02 13:00:03 -08001200 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1201 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001202
1203 mPrimaryDispSync.reset();
1204 mPrimaryDispSync.setPeriod(period);
1205
1206 if (!mPrimaryHWVsyncEnabled) {
1207 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001208 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1209 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001210 mPrimaryHWVsyncEnabled = true;
1211 }
1212}
1213
Jesse Hall948fe0c2013-10-14 12:56:09 -07001214void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001215 Mutex::Autolock _l(mHWVsyncLock);
1216 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001217 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1218 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001219 mPrimaryDispSync.endResync();
1220 mPrimaryHWVsyncEnabled = false;
1221 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001222 if (makeUnavailable) {
1223 mHWVsyncAvailable = false;
1224 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225}
1226
Tim Murray4a4e4a22016-04-19 16:29:23 +00001227void SurfaceFlinger::resyncWithRateLimit() {
1228 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001229
1230 // No explicit locking is needed here since EventThread holds a lock while calling this method
1231 static nsecs_t sLastResyncAttempted = 0;
1232 const nsecs_t now = systemTime();
1233 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001234 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001235 }
Dan Stoza57164302017-05-08 14:03:54 -07001236 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001237}
1238
Steven Thomasb02664d2017-07-26 18:48:28 -07001239void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1240 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001241 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001242 // Ignore any vsyncs from a previous hardware composer.
1243 if (sequenceId != mComposerSequenceId) {
1244 return;
1245 }
1246
1247 int32_t type;
1248 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001249 return;
1250 }
1251
Jamie Gennisd1700752013-10-14 12:22:52 -07001252 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001253
Jamie Gennisd1700752013-10-14 12:22:52 -07001254 { // Scope for the lock
1255 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001256 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001257 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001258 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001259 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001260
1261 if (needsHwVsync) {
1262 enableHardwareVsync();
1263 } else {
1264 disableHardwareVsync(false);
1265 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001266}
1267
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001268void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001269 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001270 *compositorTiming = mCompositorTiming;
1271}
1272
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001273void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001274 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001275 wp<IBinder> token = mBuiltinDisplays[type];
1276
1277 // All non-virtual displays are currently considered secure.
1278 const bool isSecure = true;
1279
1280 sp<IGraphicBufferProducer> producer;
1281 sp<IGraphicBufferConsumer> consumer;
1282 BufferQueue::createBufferQueue(&producer, &consumer);
1283
1284 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1285
1286 bool hasWideColorModes = false;
1287 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1288 for (android_color_mode_t colorMode : modes) {
1289 switch (colorMode) {
1290 case HAL_COLOR_MODE_DISPLAY_P3:
1291 case HAL_COLOR_MODE_ADOBE_RGB:
1292 case HAL_COLOR_MODE_DCI_P3:
1293 hasWideColorModes = true;
1294 break;
1295 default:
1296 break;
1297 }
1298 }
Romain Guy54f154a2017-10-24 21:40:32 +01001299 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001300 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1301 token, fbs, producer, mRenderEngine->getEGLConfig(),
Romain Guy54f154a2017-10-24 21:40:32 +01001302 useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001303 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001304 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001305 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001306 defaultColorMode = HAL_COLOR_MODE_SRGB;
1307 }
1308 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001309 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001310
1311 // Add the primary display token to mDrawingState so we don't try to
1312 // recreate the DisplayDevice for the primary display.
1313 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1314
1315 // make the GLContext current so that we can create textures when creating
1316 // Layers (which may happens before we render something)
1317 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001318}
1319
Steven Thomasb02664d2017-07-26 18:48:28 -07001320void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1321 hwc2_display_t display, HWC2::Connection connection,
1322 bool primaryDisplay) {
1323 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1324 sequenceId, display,
1325 connection == HWC2::Connection::Connected ?
1326 "connected" : "disconnected",
1327 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001328
Steven Thomasb02664d2017-07-26 18:48:28 -07001329 // Only lock if we're not on the main thread. This function is normally
1330 // called on a hwbinder thread, but for the primary display it's called on
1331 // the main thread with the state lock already held, so don't attempt to
1332 // acquire it here.
1333 ConditionalLock lock(mStateLock,
1334 std::this_thread::get_id() != mMainThreadId);
1335
1336 if (primaryDisplay) {
1337 mHwc->onHotplug(display, connection);
1338 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1339 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001340 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001341 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001342 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 if (sequenceId != mComposerSequenceId) {
1344 return;
1345 }
1346 if (mHwc->isUsingVrComposer()) {
1347 ALOGE("External displays are not supported by the vr hardware composer.");
1348 return;
1349 }
1350 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001351 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001352 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001353 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001354 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001355 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1356 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001357 }
1358 setTransactionFlags(eDisplayTransactionNeeded);
1359
Andy McFadden9e9689c2012-10-10 18:17:51 -07001360 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001361 }
Mathias Agopian86303202012-07-24 22:46:10 -07001362}
1363
Steven Thomasb02664d2017-07-26 18:48:28 -07001364void SurfaceFlinger::onRefreshReceived(int sequenceId,
1365 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001366 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 if (sequenceId != mComposerSequenceId) {
1368 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001369 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001370 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001371}
1372
Dan Stoza9e56aa02015-11-02 13:00:03 -08001373void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001374 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001376 getHwComposer().setVsyncEnabled(disp,
1377 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001378}
1379
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001380// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001381void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001383 // Clear the drawing state so that the logic inside of
1384 // handleTransactionLocked will fire. It will determine the delta between
1385 // mCurrentState and mDrawingState and re-apply all changes when we make the
1386 // transition.
1387 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389 mDisplays.clear();
1390}
1391
Steven Thomas050b2c82017-03-06 11:45:16 -08001392void SurfaceFlinger::updateVrFlinger() {
1393 if (!mVrFlinger)
1394 return;
1395 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1396 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001397 return;
1398 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1401 ALOGE("Vr flinger is only supported for remote hardware composer"
1402 " service connections. Ignoring request to transition to vr"
1403 " flinger.");
1404 mVrFlingerRequestsDisplay = false;
1405 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001406 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001409
Steven Thomasb02664d2017-07-26 18:48:28 -07001410 int currentDisplayPowerMode = getDisplayDeviceLocked(
1411 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001412
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001414 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416
Steven Thomasb02664d2017-07-26 18:48:28 -07001417 resetDisplayState();
1418 mHwc.reset(); // Delete the current instance before creating the new one
1419 mHwc.reset(new HWComposer(
1420 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1421 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001422
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1424 "Switched to non-remote hardware composer");
1425
1426 if (vrFlingerRequestsDisplay) {
1427 mVrFlinger->GrantDisplayOwnership();
1428 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001430 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001431
1432 mVisibleRegionsDirty = true;
1433 invalidateHwcGeometry();
1434
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001435 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1437 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1438 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001439
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 // Reset the timing values to account for the period of the swapped in HWC
1441 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1442 const nsecs_t period = activeConfig->getVsyncPeriod();
1443 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001444
Steven Thomasb02664d2017-07-26 18:48:28 -07001445 // Use phase of 0 since phase is not known.
1446 // Use latency of 0, which will snap to the ideal latency.
1447 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001448
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001449 android_atomic_or(1, &mRepaintEverything);
1450 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001451}
1452
Mathias Agopian4fec8732012-06-29 14:12:52 -07001453void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001454 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001455 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001456 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001457 bool frameMissed = !mHadClientComposition &&
1458 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001459 (mPreviousPresentFence->getSignalTime() ==
1460 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001461 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001462 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001463 signalLayerUpdate();
1464 break;
1465 }
1466
Steven Thomas050b2c82017-03-06 11:45:16 -08001467 // Now that we're going to make it to the handleMessageTransaction()
1468 // call below it's safe to call updateVrFlinger(), which will
1469 // potentially trigger a display handoff.
1470 updateVrFlinger();
1471
Dan Stoza6b9454d2014-11-07 16:00:59 -08001472 bool refreshNeeded = handleMessageTransaction();
1473 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001474 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001475 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001476 // Signal a refresh if a transaction modified the window state,
1477 // a new buffer was latched, or if HWC has requested a full
1478 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001479 signalRefresh();
1480 }
1481 break;
1482 }
1483 case MessageQueue::REFRESH: {
1484 handleMessageRefresh();
1485 break;
1486 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001487 }
1488}
1489
Dan Stoza6b9454d2014-11-07 16:00:59 -08001490bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001491 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001492 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001493 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001494 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001495 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001497}
1498
Dan Stoza6b9454d2014-11-07 16:00:59 -08001499bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001500 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001501 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001502}
1503
1504void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001505 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001506
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001507 mRefreshPending = false;
1508
Pablo Ceballos40845df2016-01-25 17:41:15 -08001509 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001510
Brian Andersond6927fb2016-07-23 23:37:30 -07001511 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001512 rebuildLayerStacks();
1513 setUpHWComposer();
1514 doDebugFlashRegions();
1515 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001516 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001517
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001518 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001519
1520 mHadClientComposition = false;
1521 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1522 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1523 mHadClientComposition = mHadClientComposition ||
1524 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1525 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001526
Dan Stoza9e56aa02015-11-02 13:00:03 -08001527 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001528}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001529
Mathias Agopiancd60f992012-08-16 16:28:27 -07001530void SurfaceFlinger::doDebugFlashRegions()
1531{
1532 // is debugging enabled
1533 if (CC_LIKELY(!mDebugRegion))
1534 return;
1535
1536 const bool repaintEverything = mRepaintEverything;
1537 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1538 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001539 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001540 // transform the dirty region into this screen's coordinate space
1541 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1542 if (!dirtyRegion.isEmpty()) {
1543 // redraw the whole screen
1544 doComposeSurfaces(hw, Region(hw->bounds()));
1545
1546 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001548 RenderEngine& engine(getRenderEngine());
1549 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1550
Mathias Agopianda27af92012-09-13 18:17:13 -07001551 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001552 }
1553 }
1554 }
1555
1556 postFramebuffer();
1557
1558 if (mDebugRegion > 1) {
1559 usleep(mDebugRegion * 1000);
1560 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001561
Dan Stoza9e56aa02015-11-02 13:00:03 -08001562 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001563 auto& displayDevice = mDisplays[displayId];
1564 if (!displayDevice->isDisplayOn()) {
1565 continue;
1566 }
1567
1568 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001569 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1570 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001571 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572}
1573
Brian Andersond6927fb2016-07-23 23:37:30 -07001574void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001575{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001576 ATRACE_CALL();
1577 ALOGV("preComposition");
1578
Mathias Agopiancd60f992012-08-16 16:28:27 -07001579 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001580 mDrawingState.traverseInZOrder([&](Layer* layer) {
1581 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582 needExtraInvalidate = true;
1583 }
Robert Carr2047fae2016-11-28 14:09:09 -08001584 });
1585
Mathias Agopiancd60f992012-08-16 16:28:27 -07001586 if (needExtraInvalidate) {
1587 signalLayerUpdate();
1588 }
1589}
1590
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001591void SurfaceFlinger::updateCompositorTiming(
1592 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1593 std::shared_ptr<FenceTime>& presentFenceTime) {
1594 // Update queue of past composite+present times and determine the
1595 // most recently known composite to present latency.
1596 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1597 nsecs_t compositeToPresentLatency = -1;
1598 while (!mCompositePresentTimes.empty()) {
1599 CompositePresentTime& cpt = mCompositePresentTimes.front();
1600 // Cached values should have been updated before calling this method,
1601 // which helps avoid duplicate syscalls.
1602 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1603 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1604 break;
1605 }
1606 compositeToPresentLatency = displayTime - cpt.composite;
1607 mCompositePresentTimes.pop();
1608 }
1609
1610 // Don't let mCompositePresentTimes grow unbounded, just in case.
1611 while (mCompositePresentTimes.size() > 16) {
1612 mCompositePresentTimes.pop();
1613 }
1614
Brian Andersond0010582017-03-07 13:20:31 -08001615 setCompositorTimingSnapped(
1616 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1617}
1618
1619void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1620 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001621 // Integer division and modulo round toward 0 not -inf, so we need to
1622 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001623 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001624 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1625 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1626
Brian Andersond0010582017-03-07 13:20:31 -08001627 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1628 if (idealLatency <= 0) {
1629 idealLatency = vsyncInterval;
1630 }
1631
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001632 // Snap the latency to a value that removes scheduling jitter from the
1633 // composition and present times, which often have >1ms of jitter.
1634 // Reducing jitter is important if an app attempts to extrapolate
1635 // something (such as user input) to an accurate diasplay time.
1636 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1637 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001638 nsecs_t bias = vsyncInterval / 2;
1639 int64_t extraVsyncs =
1640 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1641 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1642 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001643
Brian Andersond0010582017-03-07 13:20:31 -08001644 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001645 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1646 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001647 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001648}
1649
1650void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001651{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001652 ATRACE_CALL();
1653 ALOGV("postComposition");
1654
Brian Anderson3546a3f2016-07-14 11:51:14 -07001655 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001656 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001657 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001658 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001659 }
1660
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001661 // |mStateLock| not needed as we are on the main thread
1662 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001663
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001664 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001665 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1666 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1667 glCompositionDoneFenceTime =
1668 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1669 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1670 } else {
1671 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1672 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001673
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001674 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001675 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1676 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1677 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001678
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001679 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1680 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1681
1682 // We use the refreshStartTime which might be sampled a little later than
1683 // when we started doing work for this frame, but that should be okay
1684 // since updateCompositorTiming has snapping logic.
1685 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001686 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001687 CompositorTiming compositorTiming;
1688 {
1689 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1690 compositorTiming = mCompositorTiming;
1691 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001692
Robert Carr2047fae2016-11-28 14:09:09 -08001693 mDrawingState.traverseInZOrder([&](Layer* layer) {
1694 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001695 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001696 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001697 recordBufferingStats(layer->getName().string(),
1698 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001699 }
Robert Carr2047fae2016-11-28 14:09:09 -08001700 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001701
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001702 if (presentFenceTime->isValid()) {
1703 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001704 enableHardwareVsync();
1705 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001706 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001707 }
1708 }
1709
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001710 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001711 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001712 enableHardwareVsync();
1713 }
1714 }
1715
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001716 if (mAnimCompositionPending) {
1717 mAnimCompositionPending = false;
1718
Brian Anderson4e606e32017-03-16 15:34:57 -07001719 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001720 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001721 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001722 } else {
1723 // The HWC doesn't support present fences, so use the refresh
1724 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001725 nsecs_t presentTime =
1726 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001727 mAnimFrameTracker.setActualPresentTime(presentTime);
1728 }
1729 mAnimFrameTracker.advanceFrame();
1730 }
Dan Stozab90cf072015-03-05 11:05:59 -08001731
1732 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1733 return;
1734 }
1735
1736 nsecs_t currentTime = systemTime();
1737 if (mHasPoweredOff) {
1738 mHasPoweredOff = false;
1739 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001740 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001741 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001742 if (numPeriods < NUM_BUCKETS - 1) {
1743 mFrameBuckets[numPeriods] += elapsedTime;
1744 } else {
1745 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1746 }
1747 mTotalTime += elapsedTime;
1748 }
1749 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001750}
1751
1752void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001753 ATRACE_CALL();
1754 ALOGV("rebuildLayerStacks");
1755
Mathias Agopiancd60f992012-08-16 16:28:27 -07001756 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001757 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001758 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001759 mVisibleRegionsDirty = false;
1760 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001761
Jeff Sharkey76488112017-02-27 14:15:18 -07001762 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1763 Region opaqueRegion;
1764 Region dirtyRegion;
1765 Vector<sp<Layer>> layersSortedByZ;
1766 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1767 const Transform& tr(displayDevice->getTransform());
1768 const Rect bounds(displayDevice->getBounds());
1769 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001770 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001771
Jeff Sharkey76488112017-02-27 14:15:18 -07001772 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001773 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1774 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001775 Region drawRegion(tr.transform(
1776 layer->visibleNonTransparentRegion));
1777 drawRegion.andSelf(bounds);
1778 if (!drawRegion.isEmpty()) {
1779 layersSortedByZ.add(layer);
1780 } else {
1781 // Clear out the HWC layer if this layer was
1782 // previously visible, but no longer is
Steven Thomasb02664d2017-07-26 18:48:28 -07001783 layer->destroyHwcLayer(
1784 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001785 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001786 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001787 // WM changes displayDevice->layerStack upon sleep/awake.
1788 // Here we make sure we delete the HWC layers even if
1789 // WM changed their layer stack.
Steven Thomasb02664d2017-07-26 18:48:28 -07001790 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001791 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001792 });
1793 }
1794 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1795 displayDevice->undefinedRegion.set(bounds);
1796 displayDevice->undefinedRegion.subtractSelf(
1797 tr.transform(opaqueRegion));
1798 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001799 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001800 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001801}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001802
Romain Guy0147a172017-06-01 13:53:56 -07001803mat4 SurfaceFlinger::computeSaturationMatrix() const {
1804 if (mSaturation == 1.0f) {
1805 return mat4();
1806 }
1807
1808 // Rec.709 luma coefficients
1809 float3 luminance{0.213f, 0.715f, 0.072f};
1810 luminance *= 1.0f - mSaturation;
1811 return mat4(
1812 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1813 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1814 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1815 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1816 );
1817}
1818
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001819// pickColorMode translates a given dataspace into the best available color mode.
1820// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001821android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001822 if (mForceNativeColorMode) {
1823 return HAL_COLOR_MODE_NATIVE;
1824 }
1825
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001826 switch (dataSpace) {
1827 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1828 // system expects.
1829 case HAL_DATASPACE_UNKNOWN:
1830 case HAL_DATASPACE_SRGB:
1831 case HAL_DATASPACE_V0_SRGB:
1832 return HAL_COLOR_MODE_SRGB;
1833 break;
1834
1835 case HAL_DATASPACE_DISPLAY_P3:
1836 return HAL_COLOR_MODE_DISPLAY_P3;
1837 break;
1838
1839 default:
1840 // TODO (courtneygo): Do we want to assert an error here?
1841 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1842 dataSpace);
1843 return HAL_COLOR_MODE_SRGB;
1844 break;
1845 }
1846}
1847
Romain Guy0147a172017-06-01 13:53:56 -07001848android_dataspace SurfaceFlinger::bestTargetDataSpace(
1849 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001850 // Only support sRGB and Display-P3 right now.
1851 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1852 return HAL_DATASPACE_DISPLAY_P3;
1853 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001854 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1855 return HAL_DATASPACE_DISPLAY_P3;
1856 }
1857 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1858 return HAL_DATASPACE_DISPLAY_P3;
1859 }
1860
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001861 return HAL_DATASPACE_V0_SRGB;
1862}
1863
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001865 ATRACE_CALL();
1866 ALOGV("setUpHWComposer");
1867
Jesse Hall028dc8f2013-08-20 16:35:32 -07001868 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001869 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1870 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1871 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1872
1873 // If nothing has changed (!dirty), don't recompose.
1874 // If something changed, but we don't currently have any visible layers,
1875 // and didn't when we last did a composition, then skip it this time.
1876 // The second rule does two things:
1877 // - When all layers are removed from a display, we'll emit one black
1878 // frame, then nothing more until we get new layers.
1879 // - When a display is created with a private layer stack, we won't
1880 // emit any black frames until a layer is added to the layer stack.
1881 bool mustRecompose = dirty && !(empty && wasEmpty);
1882
1883 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1884 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1885 mustRecompose ? "doing" : "skipping",
1886 dirty ? "+" : "-",
1887 empty ? "+" : "-",
1888 wasEmpty ? "+" : "-");
1889
Dan Stoza71433162014-02-04 16:22:36 -08001890 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001891
1892 if (mustRecompose) {
1893 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1894 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001895 }
1896
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 // build the h/w work list
1898 if (CC_UNLIKELY(mGeometryInvalid)) {
1899 mGeometryInvalid = false;
1900 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1901 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1902 const auto hwcId = displayDevice->getHwcDisplayId();
1903 if (hwcId >= 0) {
1904 const Vector<sp<Layer>>& currentLayers(
1905 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001906 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001907 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001908 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001909 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001910 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001911 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001912 }
1913 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001914
Robert Carrae060832016-11-28 10:51:00 -08001915 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001916 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001917 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001918 }
1919 }
1920 }
1921 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001922 }
Riley Andrews03414a12014-07-01 14:22:59 -07001923
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001924
Romain Guy0147a172017-06-01 13:53:56 -07001925 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001926
Dan Stoza9e56aa02015-11-02 13:00:03 -08001927 // Set the per-frame data
1928 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1929 auto& displayDevice = mDisplays[displayId];
1930 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001931
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932 if (hwcId < 0) {
1933 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001934 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001935 if (colorMatrix != mPreviousColorMatrix) {
1936 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1937 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1938 "display %zd: %d", displayId, result);
1939 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1941 layer->setPerFrameData(displayDevice);
1942 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001943
1944 if (hasWideColorDisplay) {
1945 android_color_mode newColorMode;
1946 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1947
1948 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1949 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1950 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1951 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1952 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1953 }
1954 newColorMode = pickColorMode(newDataSpace);
1955
Thierry Strudel2924d012017-08-14 15:19:37 -07001956 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001957 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001958 }
1959
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001960 mPreviousColorMatrix = colorMatrix;
1961
Dan Stoza9e56aa02015-11-02 13:00:03 -08001962 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001963 auto& displayDevice = mDisplays[displayId];
1964 if (!displayDevice->isDisplayOn()) {
1965 continue;
1966 }
1967
1968 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001969 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1970 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001971 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001972}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001973
Mathias Agopiancd60f992012-08-16 16:28:27 -07001974void SurfaceFlinger::doComposition() {
1975 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001976 ALOGV("doComposition");
1977
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001978 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001979 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001980 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001981 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001982 // transform the dirty region into this screen's coordinate space
1983 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001984
1985 // repaint the framebuffer (if needed)
1986 doDisplayComposition(hw, dirtyRegion);
1987
Mathias Agopiancd60f992012-08-16 16:28:27 -07001988 hw->dirtyRegion.clear();
1989 hw->flip(hw->swapRegion);
1990 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001991 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001992 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001993 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001994}
1995
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001996void SurfaceFlinger::postFramebuffer()
1997{
Mathias Agopian841cde52012-03-01 15:44:37 -08001998 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001999 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002000
Mathias Agopiana44b0412011-10-16 18:46:35 -07002001 const nsecs_t now = systemTime();
2002 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002003
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2005 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002006 if (!displayDevice->isDisplayOn()) {
2007 continue;
2008 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002009 const auto hwcId = displayDevice->getHwcDisplayId();
2010 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002011 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002012 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002013 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002014 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002015 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2016 sp<Fence> releaseFence = Fence::NO_FENCE;
2017 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
2018 releaseFence = displayDevice->getClientTargetAcquireFence();
2019 } else {
2020 auto hwcLayer = layer->getHwcLayer(hwcId);
2021 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002022 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002023 layer->onLayerDisplayed(releaseFence);
2024 }
2025 if (hwcId >= 0) {
2026 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002027 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002028 }
2029
Mathias Agopiana44b0412011-10-16 18:46:35 -07002030 mLastSwapBufferTime = systemTime() - now;
2031 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002032
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002033 // |mStateLock| not needed as we are on the main thread
2034 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002035 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2036 logFrameStats();
2037 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002038}
2039
Mathias Agopian87baae12012-07-31 12:38:26 -07002040void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002041{
Mathias Agopian841cde52012-03-01 15:44:37 -08002042 ATRACE_CALL();
2043
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002044 // here we keep a copy of the drawing state (that is the state that's
2045 // going to be overwritten by handleTransactionLocked()) outside of
2046 // mStateLock so that the side-effects of the State assignment
2047 // don't happen with mStateLock held (which can cause deadlocks).
2048 State drawingState(mDrawingState);
2049
Mathias Agopianca4d3602011-05-19 15:38:14 -07002050 Mutex::Autolock _l(mStateLock);
2051 const nsecs_t now = systemTime();
2052 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002053
Mathias Agopianca4d3602011-05-19 15:38:14 -07002054 // Here we're guaranteed that some transaction flags are set
2055 // so we can call handleTransactionLocked() unconditionally.
2056 // We call getTransactionFlags(), which will also clear the flags,
2057 // with mStateLock held to guarantee that mCurrentState won't change
2058 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002059
Mathias Agopiane57f2922012-08-09 16:29:12 -07002060 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002061 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002062
Mathias Agopianca4d3602011-05-19 15:38:14 -07002063 mLastTransactionTime = systemTime() - now;
2064 mDebugInTransaction = 0;
2065 invalidateHwcGeometry();
2066 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002067}
2068
Mathias Agopian87baae12012-07-31 12:38:26 -07002069void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002070{
Dan Stoza7dde5992015-05-22 09:51:44 -07002071 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002072 mCurrentState.traverseInZOrder([](Layer* layer) {
2073 layer->notifyAvailableFrames();
2074 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002075
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002076 /*
2077 * Traversal of the children
2078 * (perform the transaction for each of them if needed)
2079 */
2080
Mathias Agopian3559b072012-08-15 13:46:03 -07002081 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002082 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002083 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002084 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002085
2086 const uint32_t flags = layer->doTransaction(0);
2087 if (flags & Layer::eVisibleRegion)
2088 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002089 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002090 }
2091
2092 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002093 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002094 */
2095
Mathias Agopiane57f2922012-08-09 16:29:12 -07002096 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002097 // here we take advantage of Vector's copy-on-write semantics to
2098 // improve performance by skipping the transaction entirely when
2099 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002100 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2101 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002102 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002103 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002104 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002105 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002106
2107 // find the displays that were removed
2108 // (ie: in drawing state but not in current state)
2109 // also handle displays that changed
2110 // (ie: displays that are in both lists)
2111 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002112 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2113 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002114 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002115 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002116 // Call makeCurrent() on the primary display so we can
2117 // be sure that nothing associated with this display
2118 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002119 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002120 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002121 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002122 if (hw != NULL)
2123 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002124 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002125 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002126 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002127 } else {
2128 ALOGW("trying to remove the main display");
2129 }
2130 } else {
2131 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002132 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002133 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002134 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2135 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002136 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002137 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002138 // recreating the DisplayDevice, so we just remove it
2139 // from the drawing state, so that it get re-added
2140 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002141 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002142 if (hw != NULL)
2143 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002144 mDisplays.removeItem(display);
2145 mDrawingState.displays.removeItemsAt(i);
2146 dc--; i--;
2147 // at this point we must loop to the next item
2148 continue;
2149 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002150
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002151 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002152 if (disp != NULL) {
2153 if (state.layerStack != draw[i].layerStack) {
2154 disp->setLayerStack(state.layerStack);
2155 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002156 if ((state.orientation != draw[i].orientation)
2157 || (state.viewport != draw[i].viewport)
2158 || (state.frame != draw[i].frame))
2159 {
2160 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002161 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002162 }
Michael Lentine47e45402014-07-18 15:34:25 -07002163 if (state.width != draw[i].width || state.height != draw[i].height) {
2164 disp->setDisplaySize(state.width, state.height);
2165 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002166 }
2167 }
2168 }
2169
2170 // find displays that were added
2171 // (ie: in current state but not in drawing state)
2172 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002173 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002174 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002175
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002176 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002177 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002178 sp<IGraphicBufferProducer> bqProducer;
2179 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002180 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002181
Dan Stoza9e56aa02015-11-02 13:00:03 -08002182 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002183 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002184 // Virtual displays without a surface are dormant:
2185 // they have external state (layer stack, projection,
2186 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002187 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002188
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002189 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002190 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002191 int width = 0;
2192 int status = state.surface->query(
2193 NATIVE_WINDOW_WIDTH, &width);
2194 ALOGE_IF(status != NO_ERROR,
2195 "Unable to query width (%d)", status);
2196 int height = 0;
2197 status = state.surface->query(
2198 NATIVE_WINDOW_HEIGHT, &height);
2199 ALOGE_IF(status != NO_ERROR,
2200 "Unable to query height (%d)", status);
2201 int intFormat = 0;
2202 status = state.surface->query(
2203 NATIVE_WINDOW_FORMAT, &intFormat);
2204 ALOGE_IF(status != NO_ERROR,
2205 "Unable to query format (%d)", status);
2206 auto format = static_cast<android_pixel_format_t>(
2207 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002208
Dan Stoza8cf150a2016-08-02 10:27:31 -07002209 mHwc->allocateVirtualDisplay(width, height, &format,
2210 &hwcId);
2211 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002212
Dan Stoza5cf424b2016-05-20 14:02:39 -07002213 // TODO: Plumb requested format back up to consumer
2214
Dan Stoza9e56aa02015-11-02 13:00:03 -08002215 sp<VirtualDisplaySurface> vds =
2216 new VirtualDisplaySurface(*mHwc,
2217 hwcId, state.surface, bqProducer,
2218 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002219
2220 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002221 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002222 }
2223 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002224 ALOGE_IF(state.surface!=NULL,
2225 "adding a supported display, but rendering "
2226 "surface is provided (%p), ignoring it",
2227 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002228
2229 hwcId = state.type;
2230 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2231 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002232 }
2233
2234 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002235 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002236 sp<DisplayDevice> hw =
2237 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2238 dispSurface, producer,
2239 mRenderEngine->getEGLConfig(),
2240 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002241 hw->setLayerStack(state.layerStack);
2242 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002243 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002244 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002245 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002246 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002247 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002248 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002249 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002250 }
2251 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002252 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002253 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002254
Mathias Agopian84300952012-11-21 16:02:13 -08002255 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2256 // The transform hint might have changed for some layers
2257 // (either because a display has changed, or because a layer
2258 // as changed).
2259 //
2260 // Walk through all the layers in currentLayers,
2261 // and update their transform hint.
2262 //
2263 // If a layer is visible only on a single display, then that
2264 // display is used to calculate the hint, otherwise we use the
2265 // default display.
2266 //
2267 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2268 // the hint is set before we acquire a buffer from the surface texture.
2269 //
2270 // NOTE: layer transactions have taken place already, so we use their
2271 // drawing state. However, SurfaceFlinger's own transaction has not
2272 // happened yet, so we must use the current state layer list
2273 // (soon to become the drawing state list).
2274 //
2275 sp<const DisplayDevice> disp;
2276 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002277 bool first = true;
2278 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002279 // NOTE: we rely on the fact that layers are sorted by
2280 // layerStack first (so we don't have to traverse the list
2281 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002282 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002283 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002284 currentlayerStack = layerStack;
2285 // figure out if this layerstack is mirrored
2286 // (more than one display) if so, pick the default display,
2287 // if not, pick the only display it's on.
2288 disp.clear();
2289 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2290 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002291 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002292 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002293 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002294 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002295 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002296 break;
2297 }
2298 }
2299 }
2300 }
Chet Haase91d25932013-04-11 15:24:55 -07002301 if (disp == NULL) {
2302 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2303 // redraw after transform hint changes. See bug 8508397.
2304
2305 // could be null when this layer is using a layerStack
2306 // that is not visible on any display. Also can occur at
2307 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002308 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002309 }
Chet Haase91d25932013-04-11 15:24:55 -07002310 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002311
2312 first = false;
2313 });
Mathias Agopian84300952012-11-21 16:02:13 -08002314 }
2315
2316
Mathias Agopian3559b072012-08-15 13:46:03 -07002317 /*
2318 * Perform our own transaction if needed
2319 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002320
2321 if (mLayersAdded) {
2322 mLayersAdded = false;
2323 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002324 mVisibleRegionsDirty = true;
2325 }
2326
2327 // some layers might have been removed, so
2328 // we need to update the regions they're exposing.
2329 if (mLayersRemoved) {
2330 mLayersRemoved = false;
2331 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002332 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002333 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002334 // this layer is not visible anymore
2335 // TODO: we could traverse the tree from front to back and
2336 // compute the actual visible region
2337 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002338 Region visibleReg;
2339 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002340 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002341 }
Robert Carr2047fae2016-11-28 14:09:09 -08002342 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002343 }
2344
2345 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002346
2347 updateCursorAsync();
2348}
2349
2350void SurfaceFlinger::updateCursorAsync()
2351{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002352 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2353 auto& displayDevice = mDisplays[displayId];
2354 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002355 continue;
2356 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002357
2358 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2359 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002360 }
2361 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002362}
2363
2364void SurfaceFlinger::commitTransaction()
2365{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002366 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002367 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002368 for (const auto& l : mLayersPendingRemoval) {
2369 recordBufferingStats(l->getName().string(),
2370 l->getOccupancyHistory(true));
2371 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002372 }
2373 mLayersPendingRemoval.clear();
2374 }
2375
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002376 // If this transaction is part of a window animation then the next frame
2377 // we composite should be considered an animation as well.
2378 mAnimCompositionPending = mAnimTransactionPending;
2379
Mathias Agopian4fec8732012-06-29 14:12:52 -07002380 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002381 mDrawingState.traverseInZOrder([](Layer* layer) {
2382 layer->commitChildList();
2383 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002384 mTransactionPending = false;
2385 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002386 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002387}
2388
Chia-I Wuab0c3192017-08-01 11:29:00 -07002389void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002390 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002391{
Mathias Agopian841cde52012-03-01 15:44:37 -08002392 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002393 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002394
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002395 Region aboveOpaqueLayers;
2396 Region aboveCoveredLayers;
2397 Region dirty;
2398
Mathias Agopian87baae12012-07-31 12:38:26 -07002399 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002400
Robert Carr2047fae2016-11-28 14:09:09 -08002401 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002402 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002403 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002404
Jesse Hall01e29052013-02-19 16:13:35 -08002405 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002406 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002407 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002408
Mathias Agopianab028732010-03-16 16:41:46 -07002409 /*
2410 * opaqueRegion: area of a surface that is fully opaque.
2411 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002412 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002413
2414 /*
2415 * visibleRegion: area of a surface that is visible on screen
2416 * and not fully transparent. This is essentially the layer's
2417 * footprint minus the opaque regions above it.
2418 * Areas covered by a translucent surface are considered visible.
2419 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002420 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002421
2422 /*
2423 * coveredRegion: area of a surface that is covered by all
2424 * visible regions above it (which includes the translucent areas).
2425 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002426 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002427
Jesse Halla8026d22012-09-25 13:25:04 -07002428 /*
2429 * transparentRegion: area of a surface that is hinted to be completely
2430 * transparent. This is only used to tell when the layer has no visible
2431 * non-transparent regions and can be removed from the layer list. It
2432 * does not affect the visibleRegion of this layer or any layers
2433 * beneath it. The hint may not be correct if apps don't respect the
2434 * SurfaceView restrictions (which, sadly, some don't).
2435 */
2436 Region transparentRegion;
2437
Mathias Agopianab028732010-03-16 16:41:46 -07002438
2439 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002440 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002441 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002442 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002443 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002444 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002445 if (!visibleRegion.isEmpty()) {
2446 // Remove the transparent area from the visible region
2447 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002448 if (tr.preserveRects()) {
2449 // transform the transparent region
2450 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002451 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002452 // transformation too complex, can't do the
2453 // transparent region optimization.
2454 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002455 }
Mathias Agopianab028732010-03-16 16:41:46 -07002456 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457
Mathias Agopianab028732010-03-16 16:41:46 -07002458 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002459 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002460 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002461 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2462 // the opaque region is the layer's footprint
2463 opaqueRegion = visibleRegion;
2464 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465 }
2466 }
2467
Mathias Agopianab028732010-03-16 16:41:46 -07002468 // Clip the covered region to the visible region
2469 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2470
2471 // Update aboveCoveredLayers for next (lower) layer
2472 aboveCoveredLayers.orSelf(visibleRegion);
2473
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002474 // subtract the opaque region covered by the layers above us
2475 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002476
2477 // compute this layer's dirty region
2478 if (layer->contentDirty) {
2479 // we need to invalidate the whole region
2480 dirty = visibleRegion;
2481 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002482 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002483 layer->contentDirty = false;
2484 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002485 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002486 * the exposed region consists of two components:
2487 * 1) what's VISIBLE now and was COVERED before
2488 * 2) what's EXPOSED now less what was EXPOSED before
2489 *
2490 * note that (1) is conservative, we start with the whole
2491 * visible region but only keep what used to be covered by
2492 * something -- which mean it may have been exposed.
2493 *
2494 * (2) handles areas that were not covered by anything but got
2495 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002496 */
Mathias Agopianab028732010-03-16 16:41:46 -07002497 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002498 const Region oldVisibleRegion = layer->visibleRegion;
2499 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002500 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2501 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502 }
2503 dirty.subtractSelf(aboveOpaqueLayers);
2504
2505 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002506 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507
Mathias Agopianab028732010-03-16 16:41:46 -07002508 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002510
Jesse Halla8026d22012-09-25 13:25:04 -07002511 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512 layer->setVisibleRegion(visibleRegion);
2513 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002514 layer->setVisibleNonTransparentRegion(
2515 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002516 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517
Mathias Agopian87baae12012-07-31 12:38:26 -07002518 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519}
2520
Chia-I Wuab0c3192017-08-01 11:29:00 -07002521void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002522 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002523 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002524 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002525 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002526 }
2527 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002528}
2529
Dan Stoza6b9454d2014-11-07 16:00:59 -08002530bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002531{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002532 ALOGV("handlePageFlip");
2533
Brian Andersond6927fb2016-07-23 23:37:30 -07002534 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002535
Mathias Agopian4fec8732012-06-29 14:12:52 -07002536 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002537 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002538 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002539
2540 // Store the set of layers that need updates. This set must not change as
2541 // buffers are being latched, as this could result in a deadlock.
2542 // Example: Two producers share the same command stream and:
2543 // 1.) Layer 0 is latched
2544 // 2.) Layer 0 gets a new frame
2545 // 2.) Layer 1 gets a new frame
2546 // 3.) Layer 1 is latched.
2547 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2548 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002549 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002550 if (layer->hasQueuedFrame()) {
2551 frameQueued = true;
2552 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002553 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002554 } else {
2555 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002556 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002557 } else {
2558 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002559 }
Robert Carr2047fae2016-11-28 14:09:09 -08002560 });
2561
Dan Stoza9e56aa02015-11-02 13:00:03 -08002562 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002563 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002564 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002565 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002566 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002567 newDataLatched = true;
2568 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002569 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002570
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002571 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002572
2573 // If we will need to wake up at some time in the future to deal with a
2574 // queued frame that shouldn't be displayed during this vsync period, wake
2575 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002576 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002577 signalLayerUpdate();
2578 }
2579
2580 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002581 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582}
2583
Mathias Agopianad456f92011-01-13 17:53:01 -08002584void SurfaceFlinger::invalidateHwcGeometry()
2585{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002586 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002587}
2588
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002589
Fabien Sanglard830b8472016-11-30 16:35:58 -08002590void SurfaceFlinger::doDisplayComposition(
2591 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002592 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593{
Dan Stoza71433162014-02-04 16:22:36 -08002594 // We only need to actually compose the display if:
2595 // 1) It is being handled by hardware composer, which may need this to
2596 // keep its virtual display state machine in sync, or
2597 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002598 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002599 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002600 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002601 return;
2602 }
2603
Dan Stoza9e56aa02015-11-02 13:00:03 -08002604 ALOGV("doDisplayComposition");
2605
Mathias Agopian87baae12012-07-31 12:38:26 -07002606 Region dirtyRegion(inDirtyRegion);
2607
Mathias Agopianb8a55602009-06-26 19:06:36 -07002608 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002609 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610
Fabien Sanglard830b8472016-11-30 16:35:58 -08002611 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002612 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002613 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2614 // takes a rectangle, we must make sure to update that whole
2615 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002616 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002617 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002618 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002619 // We need to redraw the rectangle that will be updated
2620 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002621 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002622 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002623 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002624 } else {
2625 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002626 dirtyRegion.set(displayDevice->bounds());
2627 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628 }
2629 }
2630
Fabien Sanglard830b8472016-11-30 16:35:58 -08002631 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002633 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002634 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002635
2636 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002637 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638}
2639
Dan Stoza9e56aa02015-11-02 13:00:03 -08002640bool SurfaceFlinger::doComposeSurfaces(
2641 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002642{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002643 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002644
Dan Stoza9e56aa02015-11-02 13:00:03 -08002645 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002646
2647 mat4 oldColorMatrix;
2648 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2649 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2650 if (applyColorMatrix) {
2651 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2652 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2653 }
2654
Dan Stoza9e56aa02015-11-02 13:00:03 -08002655 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2656 if (hasClientComposition) {
2657 ALOGV("hasClientComposition");
2658
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002659#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01002660 mRenderEngine->setWideColor(
2661 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2662 mRenderEngine->setColorMode(mForceNativeColorMode ?
2663 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002664#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002665 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002666 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002667 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002668 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002669
2670 // |mStateLock| not needed as we are on the main thread
2671 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002672 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2673 }
2674 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002675 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002676
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002677 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002678 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2679 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002680 // when using overlays, we assume a fully transparent framebuffer
2681 // NOTE: we could reduce how much we need to clear, for instance
2682 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002683 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002684 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002685 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002686 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002687 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002688 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002689
2690 // we remove the scissor part
2691 // we're left with the letterbox region
2692 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002694
2695 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002696 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002697
2698 // but limit it to the dirty region
2699 region.andSelf(dirty);
2700
Mathias Agopianb9494d52012-04-18 02:28:45 -07002701 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002702 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002703 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002704 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002705 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002706 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002707
Dan Stoza9e56aa02015-11-02 13:00:03 -08002708 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002709 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002710 // scissor on the main display. It should never be needed
2711 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002712 const Rect& bounds(displayDevice->getBounds());
2713 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002714 if (scissor != bounds) {
2715 // scissor doesn't match the screen's dimensions, so we
2716 // need to clear everything outside of it and enable
2717 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002718
Mathias Agopianf45c5102012-10-24 16:29:17 -07002719 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002720 const uint32_t height = displayDevice->getHeight();
2721 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002722 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002723 }
2724 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002725 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002726
Mathias Agopian85d751c2012-08-29 16:59:24 -07002727 /*
2728 * and then, render the layers targeted at the framebuffer
2729 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002730
Dan Stoza9e56aa02015-11-02 13:00:03 -08002731 ALOGV("Rendering client layers");
2732 const Transform& displayTransform = displayDevice->getTransform();
2733 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002734 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002735 bool firstLayer = true;
2736 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2737 const Region clip(dirty.intersect(
2738 displayTransform.transform(layer->visibleRegion)));
2739 ALOGV("Layer: %s", layer->getName().string());
2740 ALOGV(" Composition type: %s",
2741 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002742 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002743 switch (layer->getCompositionType(hwcId)) {
2744 case HWC2::Composition::Cursor:
2745 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002746 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002747 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002748 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002749 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002750 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002751 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002752 // never clear the very first layer since we're
2753 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002754 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002755 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002756 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002757 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002758 case HWC2::Composition::Client: {
2759 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002760 break;
2761 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002762 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002763 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002764 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002765 } else {
2766 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002767 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002768 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002769 }
2770 } else {
2771 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002772 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002773 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002774 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002775 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002776 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002777 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002778 }
2779 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002780
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002781 if (applyColorMatrix) {
2782 getRenderEngine().setupColorTransform(oldColorMatrix);
2783 }
2784
Mathias Agopianf45c5102012-10-24 16:29:17 -07002785 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002786 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002787 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788}
2789
Fabien Sanglard830b8472016-11-30 16:35:58 -08002790void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2791 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002792 RenderEngine& engine(getRenderEngine());
2793 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794}
2795
Dan Stoza7d89d062015-04-30 13:29:25 -07002796status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002797 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002798 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002799 const sp<Layer>& lbc,
2800 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002801{
Dan Stoza7d89d062015-04-30 13:29:25 -07002802 // add this layer to the current state list
2803 {
2804 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002805 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002806 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2807 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002808 return NO_MEMORY;
2809 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002810 if (parent == nullptr) {
2811 mCurrentState.layersSortedByZ.add(lbc);
2812 } else {
chaviwc9674332017-08-28 12:32:18 -07002813 bool found = false;
2814 mCurrentState.traverseInZOrder([&](Layer* layer) {
2815 if (layer == parent.get()) {
2816 found = true;
2817 }
2818 });
2819
2820 if (!found) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002821 ALOGE("addClientLayer called with a removed parent");
2822 return NAME_NOT_FOUND;
2823 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002824 parent->addChild(lbc);
2825 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002826
Dan Stoza7d89d062015-04-30 13:29:25 -07002827 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002828 mLayersAdded = true;
2829 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002830 }
2831
Mathias Agopian96f08192010-06-02 23:28:45 -07002832 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002833 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002834
Dan Stoza7d89d062015-04-30 13:29:25 -07002835 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002836}
2837
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002838status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002839 Mutex::Autolock _l(mStateLock);
2840
Robert Carr1f0a16a2016-10-24 16:27:39 -07002841 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002842 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002843 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002844 if (topLevelOnly) {
2845 return NO_ERROR;
2846 }
2847
Chia-I Wu98f1c102017-05-30 14:54:08 -07002848 sp<Layer> ancestor = p;
2849 while (ancestor->getParent() != nullptr) {
2850 ancestor = ancestor->getParent();
2851 }
2852 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2853 ALOGE("removeLayer called with a layer whose parent has been removed");
2854 return NAME_NOT_FOUND;
2855 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002856
2857 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002858 } else {
2859 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002860 }
2861
Robert Carr136e2f62017-02-08 17:54:29 -08002862 // As a matter of normal operation, the LayerCleaner will produce a second
2863 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2864 // so we will succeed in promoting it, but it's already been removed
2865 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2866 // otherwise something has gone wrong and we are leaking the layer.
2867 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002868 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2869 layer->getName().string(),
2870 (p != nullptr) ? p->getName().string() : "no-parent");
2871 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002872 } else if (index < 0) {
2873 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002874 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002875
Chia-I Wuc6657022017-08-15 11:18:17 -07002876 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002877 mLayersPendingRemoval.add(layer);
2878 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002879 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002880 setTransactionFlags(eTransactionNeeded);
2881 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882}
2883
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002884uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002885 return android_atomic_release_load(&mTransactionFlags);
2886}
2887
Mathias Agopian3f844832013-08-07 21:24:32 -07002888uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2890}
2891
Mathias Agopian3f844832013-08-07 21:24:32 -07002892uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2894 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002895 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896 }
2897 return old;
2898}
2899
Mathias Agopian8b33f032012-07-24 20:43:54 -07002900void SurfaceFlinger::setTransactionState(
2901 const Vector<ComposerState>& state,
2902 const Vector<DisplayState>& displays,
2903 uint32_t flags)
2904{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002905 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002906 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002907 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002908
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002909 if (flags & eAnimation) {
2910 // For window updates that are part of an animation we must wait for
2911 // previous animation "frames" to be handled.
2912 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002913 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002914 if (CC_UNLIKELY(err != NO_ERROR)) {
2915 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002916 // caller after a few seconds.
2917 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2918 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002919 mAnimTransactionPending = false;
2920 break;
2921 }
2922 }
2923 }
2924
Mathias Agopiane57f2922012-08-09 16:29:12 -07002925 size_t count = displays.size();
2926 for (size_t i=0 ; i<count ; i++) {
2927 const DisplayState& s(displays[i]);
2928 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002929 }
2930
Mathias Agopiane57f2922012-08-09 16:29:12 -07002931 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002932 for (size_t i=0 ; i<count ; i++) {
2933 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002934 // Here we need to check that the interface we're given is indeed
2935 // one of our own. A malicious client could give us a NULL
2936 // IInterface, or one of its own or even one of our own but a
2937 // different type. All these situations would cause us to crash.
2938 //
2939 // NOTE: it would be better to use RTTI as we could directly check
2940 // that we have a Client*. however, RTTI is disabled in Android.
2941 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002942 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002943 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002944 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002945 sp<Client> client( static_cast<Client *>(s.client.get()) );
2946 transactionFlags |= setClientStateLocked(client, s.state);
2947 }
2948 }
2949 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002950 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002951
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002952 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2953 // anyway. This can be used as a flush mechanism for previous async transactions.
2954 // Empty animation transaction can be used to simulate back-pressure, so also force a
2955 // transaction for empty animation transactions.
2956 if (transactionFlags == 0 &&
2957 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002958 transactionFlags = eTransactionNeeded;
2959 }
2960
Mathias Agopian386aa982011-11-07 21:58:03 -08002961 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002962 if (mInterceptor.isEnabled()) {
2963 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2964 }
Irvel468051e2016-06-13 16:44:44 -07002965
Mathias Agopian386aa982011-11-07 21:58:03 -08002966 // this triggers the transaction
2967 setTransactionFlags(transactionFlags);
2968
2969 // if this is a synchronous transaction, wait for it to take effect
2970 // before returning.
2971 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002972 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002973 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002974 if (flags & eAnimation) {
2975 mAnimTransactionPending = true;
2976 }
2977 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002978 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2979 if (CC_UNLIKELY(err != NO_ERROR)) {
2980 // just in case something goes wrong in SF, return to the
2981 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002982 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2983 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002984 break;
2985 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002986 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002987 }
2988}
2989
Mathias Agopiane57f2922012-08-09 16:29:12 -07002990uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2991{
Jesse Hall9a143922012-10-04 16:29:19 -07002992 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2993 if (dpyIdx < 0)
2994 return 0;
2995
Mathias Agopiane57f2922012-08-09 16:29:12 -07002996 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002997 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002998 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002999 const uint32_t what = s.what;
3000 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003001 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003002 disp.surface = s.surface;
3003 flags |= eDisplayTransactionNeeded;
3004 }
3005 }
3006 if (what & DisplayState::eLayerStackChanged) {
3007 if (disp.layerStack != s.layerStack) {
3008 disp.layerStack = s.layerStack;
3009 flags |= eDisplayTransactionNeeded;
3010 }
3011 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003012 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003013 if (disp.orientation != s.orientation) {
3014 disp.orientation = s.orientation;
3015 flags |= eDisplayTransactionNeeded;
3016 }
3017 if (disp.frame != s.frame) {
3018 disp.frame = s.frame;
3019 flags |= eDisplayTransactionNeeded;
3020 }
3021 if (disp.viewport != s.viewport) {
3022 disp.viewport = s.viewport;
3023 flags |= eDisplayTransactionNeeded;
3024 }
3025 }
Michael Lentine47e45402014-07-18 15:34:25 -07003026 if (what & DisplayState::eDisplaySizeChanged) {
3027 if (disp.width != s.width) {
3028 disp.width = s.width;
3029 flags |= eDisplayTransactionNeeded;
3030 }
3031 if (disp.height != s.height) {
3032 disp.height = s.height;
3033 flags |= eDisplayTransactionNeeded;
3034 }
3035 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003036 }
3037 return flags;
3038}
3039
3040uint32_t SurfaceFlinger::setClientStateLocked(
3041 const sp<Client>& client,
3042 const layer_state_t& s)
3043{
3044 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003045 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003046 if (layer != 0) {
3047 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003048 bool geometryAppliesWithResize =
3049 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003050 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003051 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003052 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003053 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003054 }
3055 if (what & layer_state_t::eLayerChanged) {
3056 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057 const auto& p = layer->getParent();
3058 if (p == nullptr) {
3059 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3060 if (layer->setLayer(s.z) && idx >= 0) {
3061 mCurrentState.layersSortedByZ.removeAt(idx);
3062 mCurrentState.layersSortedByZ.add(layer);
3063 // we need traversal (state changed)
3064 // AND transaction (list changed)
3065 flags |= eTransactionNeeded|eTraversalNeeded;
3066 }
3067 } else {
3068 if (p->setChildLayer(layer, s.z)) {
3069 flags |= eTransactionNeeded|eTraversalNeeded;
3070 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003071 }
3072 }
Robert Carrdb66e622017-04-10 16:55:57 -07003073 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003074 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003075 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003076 mCurrentState.layersSortedByZ.removeAt(idx);
3077 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003078 flags |= eTransactionNeeded|eTraversalNeeded;
3079 }
3080 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003081 if (what & layer_state_t::eSizeChanged) {
3082 if (layer->setSize(s.w, s.h)) {
3083 flags |= eTraversalNeeded;
3084 }
3085 }
3086 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003087 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003088 flags |= eTraversalNeeded;
3089 }
chaviw13fdc492017-06-27 12:40:18 -07003090 if (what & layer_state_t::eColorChanged) {
3091 if (layer->setColor(s.color))
3092 flags |= eTraversalNeeded;
3093 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003094 if (what & layer_state_t::eMatrixChanged) {
3095 if (layer->setMatrix(s.matrix))
3096 flags |= eTraversalNeeded;
3097 }
3098 if (what & layer_state_t::eTransparentRegionChanged) {
3099 if (layer->setTransparentRegionHint(s.transparentRegion))
3100 flags |= eTraversalNeeded;
3101 }
Dan Stoza23116082015-06-18 14:58:39 -07003102 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003103 if (layer->setFlags(s.flags, s.mask))
3104 flags |= eTraversalNeeded;
3105 }
3106 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003107 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003108 flags |= eTraversalNeeded;
3109 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003110 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003111 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003112 flags |= eTraversalNeeded;
3113 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003114 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003115 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003116 // We only allow setting layer stacks for top level layers,
3117 // everything else inherits layer stack from its parent.
3118 if (layer->hasParent()) {
3119 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3120 layer->getName().string());
3121 } else if (idx < 0) {
3122 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3123 "that also does not appear in the top level layer list. Something"
3124 " has gone wrong.", layer->getName().string());
3125 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003126 mCurrentState.layersSortedByZ.removeAt(idx);
3127 mCurrentState.layersSortedByZ.add(layer);
3128 // we need traversal (state changed)
3129 // AND transaction (list changed)
3130 flags |= eTransactionNeeded|eTraversalNeeded;
3131 }
3132 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003133 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003134 if (s.barrierHandle != nullptr) {
3135 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3136 } else if (s.barrierGbp != nullptr) {
3137 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3138 if (authenticateSurfaceTextureLocked(gbp)) {
3139 const auto& otherLayer =
3140 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3141 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3142 } else {
3143 ALOGE("Attempt to defer transaction to to an"
3144 " unrecognized GraphicBufferProducer");
3145 }
3146 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003147 // 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 }
chaviwf1961f72017-09-18 16:41:07 -07003150 if (what & layer_state_t::eReparent) {
3151 if (layer->reparent(s.parentHandleForChild)) {
chaviw06178942017-07-27 10:25:59 -07003152 flags |= eTransactionNeeded|eTraversalNeeded;
3153 }
3154 }
Robert Carr1db73f62016-12-21 12:58:51 -08003155 if (what & layer_state_t::eReparentChildren) {
3156 if (layer->reparentChildren(s.reparentHandle)) {
3157 flags |= eTransactionNeeded|eTraversalNeeded;
3158 }
3159 }
Robert Carr9524cb32017-02-13 11:32:32 -08003160 if (what & layer_state_t::eDetachChildren) {
3161 layer->detachChildren();
3162 }
Robert Carrc3574f72016-03-24 12:19:32 -07003163 if (what & layer_state_t::eOverrideScalingModeChanged) {
3164 layer->setOverrideScalingMode(s.overrideScalingMode);
3165 // We don't trigger a traversal here because if no other state is
3166 // changed, we don't want this to cause any more work
3167 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003168 }
3169 return flags;
3170}
3171
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003172status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003173 const String8& name,
3174 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003175 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003176 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3177 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003179 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003180 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003181 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003182 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003183 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003184
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003185 status_t result = NO_ERROR;
3186
3187 sp<Layer> layer;
3188
Cody Northropbc755282017-03-31 12:00:08 -06003189 String8 uniqueName = getUniqueLayerName(name);
3190
Mathias Agopian3165cc22012-08-08 19:42:09 -07003191 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3192 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003193 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003194 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003195 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196 break;
chaviw13fdc492017-06-27 12:40:18 -07003197 case ISurfaceComposerClient::eFXSurfaceColor:
3198 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003199 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003200 handle, gbp, &layer);
3201 break;
3202 default:
3203 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204 break;
3205 }
3206
Dan Stoza7d89d062015-04-30 13:29:25 -07003207 if (result != NO_ERROR) {
3208 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003209 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003210
Chia-I Wuab0c3192017-08-01 11:29:00 -07003211 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3212 // TODO b/64227542
3213 if (windowType == 441731) {
3214 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3215 layer->setPrimaryDisplayOnly();
3216 }
3217
Albert Chaulk479c60c2017-01-27 14:21:34 -05003218 layer->setInfo(windowType, ownerUid);
3219
Robert Carr1f0a16a2016-10-24 16:27:39 -07003220 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003221 if (result != NO_ERROR) {
3222 return result;
3223 }
Irvelffc9efc2016-07-27 15:16:37 -07003224 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003225
3226 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003227 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228}
3229
Cody Northropbc755282017-03-31 12:00:08 -06003230String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3231{
3232 bool matchFound = true;
3233 uint32_t dupeCounter = 0;
3234
3235 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3236 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3237
3238 // Loop over layers until we're sure there is no matching name
3239 while (matchFound) {
3240 matchFound = false;
3241 mDrawingState.traverseInZOrder([&](Layer* layer) {
3242 if (layer->getName() == uniqueName) {
3243 matchFound = true;
3244 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3245 }
3246 });
3247 }
3248
3249 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3250
3251 return uniqueName;
3252}
3253
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003254status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3255 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3256 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003257{
3258 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003259 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003260 case PIXEL_FORMAT_TRANSPARENT:
3261 case PIXEL_FORMAT_TRANSLUCENT:
3262 format = PIXEL_FORMAT_RGBA_8888;
3263 break;
3264 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003265 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003266 break;
3267 }
3268
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003269 *outLayer = new Layer(this, client, name, w, h, flags);
3270 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3271 if (err == NO_ERROR) {
3272 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003273 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003275
3276 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3277 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278}
3279
chaviw13fdc492017-06-27 12:40:18 -07003280status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003281 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3282 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283{
chaviw13fdc492017-06-27 12:40:18 -07003284 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003285 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003286 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003287 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003288}
3289
Mathias Agopianac9fa422013-02-11 16:40:36 -08003290status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291{
Robert Carr9524cb32017-02-13 11:32:32 -08003292 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003293 status_t err = NO_ERROR;
3294 sp<Layer> l(client->getLayerUser(handle));
3295 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003296 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003297 err = removeLayer(l);
3298 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3299 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003300 }
3301 return err;
3302}
3303
Mathias Agopian13127d82013-03-05 17:47:11 -08003304status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003305{
Mathias Agopian67106042013-03-14 19:18:13 -07003306 // called by ~LayerCleaner() when all references to the IBinder (handle)
3307 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003308 sp<Layer> l = layer.promote();
3309 if (l == nullptr) {
3310 // The layer has already been removed, carry on
3311 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003312 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003313 // If we have a parent, then we can continue to live as long as it does.
3314 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003315}
3316
Mathias Agopianb60314a2012-04-10 22:09:54 -07003317// ---------------------------------------------------------------------------
3318
Andy McFadden13a082e2012-08-24 10:16:42 -07003319void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003320 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003321 Vector<ComposerState> state;
3322 Vector<DisplayState> displays;
3323 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003324 d.what = DisplayState::eDisplayProjectionChanged |
3325 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003326 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003327 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003328 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003329 d.frame.makeInvalid();
3330 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003331 d.width = 0;
3332 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003333 displays.add(d);
3334 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003335 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3336 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003337
Dan Stoza9e56aa02015-11-02 13:00:03 -08003338 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3339 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003340 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003341
Brian Andersond0010582017-03-07 13:20:31 -08003342 // Use phase of 0 since phase is not known.
3343 // Use latency of 0, which will snap to the ideal latency.
3344 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003345}
3346
3347void SurfaceFlinger::initializeDisplays() {
3348 class MessageScreenInitialized : public MessageBase {
3349 SurfaceFlinger* flinger;
3350 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003351 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003352 virtual bool handler() {
3353 flinger->onInitializeDisplays();
3354 return true;
3355 }
3356 };
3357 sp<MessageBase> msg = new MessageScreenInitialized(this);
3358 postMessageAsync(msg); // we may be called from main thread, use async message
3359}
3360
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003361void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003362 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003363 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3364 this);
3365 int32_t type = hw->getDisplayType();
3366 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003367
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003368 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003369 return;
3370 }
3371
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003372 hw->setPowerMode(mode);
3373 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3374 ALOGW("Trying to set power mode for virtual display");
3375 return;
3376 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003377
Irvelffc9efc2016-07-27 15:16:37 -07003378 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003379 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003380 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3381 if (idx < 0) {
3382 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3383 return;
3384 }
3385 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3386 }
3387
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003388 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003389 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003390 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003391 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3392 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003393 // FIXME: eventthread only knows about the main display right now
3394 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003395 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003396 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003397
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003398 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003399 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003400 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003401
3402 struct sched_param param = {0};
3403 param.sched_priority = 1;
3404 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3405 ALOGW("Couldn't set SCHED_FIFO on display on");
3406 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003407 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003408 // Turn off the display
3409 struct sched_param param = {0};
3410 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3411 ALOGW("Couldn't set SCHED_OTHER on display off");
3412 }
3413
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003414 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003415 disableHardwareVsync(true); // also cancels any in-progress resync
3416
Mathias Agopiancde87a32012-09-13 14:09:01 -07003417 // FIXME: eventthread only knows about the main display right now
3418 mEventThread->onScreenReleased();
3419 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003420
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003421 getHwComposer().setPowerMode(type, mode);
3422 mVisibleRegionsDirty = true;
3423 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003424 } else if (mode == HWC_POWER_MODE_DOZE ||
3425 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003426 // Update display while dozing
3427 getHwComposer().setPowerMode(type, mode);
3428 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3429 // FIXME: eventthread only knows about the main display right now
3430 mEventThread->onScreenAcquired();
3431 resyncToHardwareVsync(true);
3432 }
3433 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3434 // Leave display going to doze
3435 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3436 disableHardwareVsync(true); // also cancels any in-progress resync
3437 // FIXME: eventthread only knows about the main display right now
3438 mEventThread->onScreenReleased();
3439 }
3440 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003441 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003442 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003443 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003444 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003445}
3446
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003447void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3448 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003449 SurfaceFlinger& mFlinger;
3450 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003451 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003452 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003453 MessageSetPowerMode(SurfaceFlinger& flinger,
3454 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3455 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003456 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003457 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003458 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003459 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003460 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003461 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003462 ALOGW("Attempt to set power mode = %d for virtual display",
3463 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003464 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003465 mFlinger.setPowerModeInternal(
3466 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003467 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003468 return true;
3469 }
3470 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003471 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003472 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003473}
3474
3475// ---------------------------------------------------------------------------
3476
Vishnu Nair35798872017-10-06 16:00:36 -07003477status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003478 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003479
Mathias Agopianbd115332013-04-18 16:41:04 -07003480 IPCThreadState* ipc = IPCThreadState::self();
3481 const int pid = ipc->getCallingPid();
3482 const int uid = ipc->getCallingUid();
3483 if ((uid != AID_SHELL) &&
3484 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003485 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003486 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003487 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003488 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003489 // (this would indicate SF is stuck, but we want to be able to
3490 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003491 status_t err = mStateLock.timedLock(s2ns(1));
3492 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003493 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003494 result.appendFormat(
3495 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3496 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003497 }
3498
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003499 bool dumpAll = true;
3500 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003501 size_t numArgs = args.size();
3502 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003503 if ((index < numArgs) &&
3504 (args[index] == String16("--list"))) {
3505 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003506 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003507 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003508 }
3509
3510 if ((index < numArgs) &&
3511 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003512 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003513 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003514 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003515 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003516
3517 if ((index < numArgs) &&
3518 (args[index] == String16("--latency-clear"))) {
3519 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003520 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003521 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003522 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003523
3524 if ((index < numArgs) &&
3525 (args[index] == String16("--dispsync"))) {
3526 index++;
3527 mPrimaryDispSync.dump(result);
3528 dumpAll = false;
3529 }
Dan Stozab90cf072015-03-05 11:05:59 -08003530
3531 if ((index < numArgs) &&
3532 (args[index] == String16("--static-screen"))) {
3533 index++;
3534 dumpStaticScreenStats(result);
3535 dumpAll = false;
3536 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003537
3538 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003539 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003540 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003541 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003542 dumpAll = false;
3543 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003544
3545 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3546 index++;
3547 dumpWideColorInfo(result);
3548 dumpAll = false;
3549 }
chaviw1d044282017-09-27 12:19:28 -07003550
3551 if ((index < numArgs) && (args[index] == String16("--proto"))) {
3552 index++;
3553 LayersProto layersProto = dumpProtoInfo();
3554 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3555 dumpAll = false;
3556 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003557 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003558
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003559 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003560 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003561 }
3562
Mathias Agopian9795c422009-08-26 16:36:26 -07003563 if (locked) {
3564 mStateLock.unlock();
3565 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003566 }
3567 write(fd, result.string(), result.size());
3568 return NO_ERROR;
3569}
3570
Dan Stozac7014012014-02-14 15:03:43 -08003571void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3572 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003573{
Robert Carr2047fae2016-11-28 14:09:09 -08003574 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003575 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003576 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003577}
3578
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003579void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003580 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003581{
3582 String8 name;
3583 if (index < args.size()) {
3584 name = String8(args[index]);
3585 index++;
3586 }
3587
Dan Stoza9e56aa02015-11-02 13:00:03 -08003588 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3589 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003590 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003591
3592 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003593 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003594 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003595 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003596 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003597 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003598 }
Robert Carr2047fae2016-11-28 14:09:09 -08003599 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003600 }
3601}
3602
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003603void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003604 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003605{
3606 String8 name;
3607 if (index < args.size()) {
3608 name = String8(args[index]);
3609 index++;
3610 }
3611
Robert Carr2047fae2016-11-28 14:09:09 -08003612 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003613 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003614 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003615 }
Robert Carr2047fae2016-11-28 14:09:09 -08003616 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003617
Svetoslavd85084b2014-03-20 10:28:31 -07003618 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003619}
3620
Jamie Gennis6547ff42013-07-16 20:12:42 -07003621// This should only be called from the main thread. Otherwise it would need
3622// the lock and should use mCurrentState rather than mDrawingState.
3623void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003624 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003625 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003626 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003627
3628 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3629}
3630
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003631void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003632{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003633 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003634 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3635
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003636 if (isLayerTripleBufferingDisabled())
3637 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003638
3639 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003640 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003641 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003642 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003643 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3644 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003645 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003646}
3647
Dan Stozab90cf072015-03-05 11:05:59 -08003648void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3649{
3650 result.appendFormat("Static screen stats:\n");
3651 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3652 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3653 float percent = 100.0f *
3654 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3655 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3656 b + 1, bucketTimeSec, percent);
3657 }
3658 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3659 float percent = 100.0f *
3660 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3661 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3662 NUM_BUCKETS - 1, bucketTimeSec, percent);
3663}
3664
Dan Stozae77c7662016-05-13 11:37:28 -07003665void SurfaceFlinger::recordBufferingStats(const char* layerName,
3666 std::vector<OccupancyTracker::Segment>&& history) {
3667 Mutex::Autolock lock(mBufferingStatsMutex);
3668 auto& stats = mBufferingStats[layerName];
3669 for (const auto& segment : history) {
3670 if (!segment.usedThirdBuffer) {
3671 stats.twoBufferTime += segment.totalTime;
3672 }
3673 if (segment.occupancyAverage < 1.0f) {
3674 stats.doubleBufferedTime += segment.totalTime;
3675 } else if (segment.occupancyAverage < 2.0f) {
3676 stats.tripleBufferedTime += segment.totalTime;
3677 }
3678 ++stats.numSegments;
3679 stats.totalTime += segment.totalTime;
3680 }
3681}
3682
Brian Andersond6927fb2016-07-23 23:37:30 -07003683void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3684 result.appendFormat("Layer frame timestamps:\n");
3685
3686 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3687 const size_t count = currentLayers.size();
3688 for (size_t i=0 ; i<count ; i++) {
3689 currentLayers[i]->dumpFrameEvents(result);
3690 }
3691}
3692
Dan Stozae77c7662016-05-13 11:37:28 -07003693void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3694 result.append("Buffering stats:\n");
3695 result.append(" [Layer name] <Active time> <Two buffer> "
3696 "<Double buffered> <Triple buffered>\n");
3697 Mutex::Autolock lock(mBufferingStatsMutex);
3698 typedef std::tuple<std::string, float, float, float> BufferTuple;
3699 std::map<float, BufferTuple, std::greater<float>> sorted;
3700 for (const auto& statsPair : mBufferingStats) {
3701 const char* name = statsPair.first.c_str();
3702 const BufferingStats& stats = statsPair.second;
3703 if (stats.numSegments == 0) {
3704 continue;
3705 }
3706 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3707 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3708 stats.totalTime;
3709 float doubleBufferRatio = static_cast<float>(
3710 stats.doubleBufferedTime) / stats.totalTime;
3711 float tripleBufferRatio = static_cast<float>(
3712 stats.tripleBufferedTime) / stats.totalTime;
3713 sorted.insert({activeTime, {name, twoBufferRatio,
3714 doubleBufferRatio, tripleBufferRatio}});
3715 }
3716 for (const auto& sortedPair : sorted) {
3717 float activeTime = sortedPair.first;
3718 const BufferTuple& values = sortedPair.second;
3719 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3720 std::get<0>(values).c_str(), activeTime,
3721 std::get<1>(values), std::get<2>(values),
3722 std::get<3>(values));
3723 }
3724 result.append("\n");
3725}
3726
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003727void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3728 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003729 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003730
3731 // TODO: print out if wide-color mode is active or not
3732
3733 for (size_t d = 0; d < mDisplays.size(); d++) {
3734 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3735 int32_t hwcId = displayDevice->getHwcDisplayId();
3736 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3737 continue;
3738 }
3739
3740 result.appendFormat("Display %d color modes:\n", hwcId);
3741 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3742 for (auto&& mode : modes) {
3743 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3744 }
3745
3746 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3747 result.appendFormat(" Current color mode: %s (%d)\n",
3748 decodeColorMode(currentMode).c_str(), currentMode);
3749 }
3750 result.append("\n");
3751}
3752
chaviw1d044282017-09-27 12:19:28 -07003753LayersProto SurfaceFlinger::dumpProtoInfo() const {
3754 LayersProto layersProto;
3755 mCurrentState.traverseInZOrder([&](Layer* layer) {
3756 LayerProto* layerProto = layersProto.add_layers();
3757 layer->writeToProto(layerProto, LayerVector::StateSet::Current);
3758 });
3759
3760 return layersProto;
3761}
3762
Mathias Agopian74d211a2013-04-22 16:55:35 +02003763void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3764 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003765{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003766 bool colorize = false;
3767 if (index < args.size()
3768 && (args[index] == String16("--color"))) {
3769 colorize = true;
3770 index++;
3771 }
3772
3773 Colorizer colorizer(colorize);
3774
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003775 // figure out if we're stuck somewhere
3776 const nsecs_t now = systemTime();
3777 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3778 const nsecs_t inTransaction(mDebugInTransaction);
3779 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3780 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3781
3782 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003783 * Dump library configuration.
3784 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003785
3786 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003787 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003788 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003789 appendSfConfigString(result);
3790 appendUiConfigString(result);
3791 appendGuiConfigString(result);
3792 result.append("\n");
3793
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003794 result.append("\nWide-Color information:\n");
3795 dumpWideColorInfo(result);
3796
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003797 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003798 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003799 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003800 result.append(SyncFeatures::getInstance().toString());
3801 result.append("\n");
3802
Dan Stoza9e56aa02015-11-02 13:00:03 -08003803 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3804
Andy McFadden41d67d72014-04-25 16:58:34 -07003805 colorizer.bold(result);
3806 result.append("DispSync configuration: ");
3807 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003808 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003809 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003810 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003811 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003812 result.append("\n");
3813
Dan Stozab90cf072015-03-05 11:05:59 -08003814 // Dump static screen stats
3815 result.append("\n");
3816 dumpStaticScreenStats(result);
3817 result.append("\n");
3818
Dan Stozae77c7662016-05-13 11:37:28 -07003819 dumpBufferingStats(result);
3820
Andy McFadden4803b742012-09-24 19:07:20 -07003821 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003822 * Dump the visible layer list
3823 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003824 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003825 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003826 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003827
3828 LayersProto layersProto = dumpProtoInfo();
3829 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3830 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003831
3832 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003833 * Dump Display state
3834 */
3835
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003836 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003837 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003838 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003839 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3840 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003841 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003842 }
3843
3844 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003845 * Dump SurfaceFlinger global state
3846 */
3847
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003848 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003849 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003850 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003851
Mathias Agopian888c8222012-08-04 21:10:38 -07003852 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003853 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003854
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003855 colorizer.bold(result);
3856 result.appendFormat("EGL implementation : %s\n",
3857 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3858 colorizer.reset(result);
3859 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003860 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003861
Mathias Agopian875d8e12013-06-07 15:35:48 -07003862 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003863
Mathias Agopian42977342012-08-05 00:40:46 -07003864 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003865 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3866 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003867 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003868 " last eglSwapBuffers() time: %f us\n"
3869 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003870 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003871 " refresh-rate : %f fps\n"
3872 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003873 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003874 " gpu_to_cpu_unsupported : %d\n"
3875 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003876 mLastSwapBufferTime/1000.0,
3877 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003878 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003879 1e9 / activeConfig->getVsyncPeriod(),
3880 activeConfig->getDpiX(),
3881 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003882 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003883
Mathias Agopian74d211a2013-04-22 16:55:35 +02003884 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003885 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003886
Mathias Agopian74d211a2013-04-22 16:55:35 +02003887 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003888 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003889
3890 /*
3891 * VSYNC state
3892 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003893 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003894 result.append("\n");
3895
3896 /*
3897 * HWC layer minidump
3898 */
3899 for (size_t d = 0; d < mDisplays.size(); d++) {
3900 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3901 int32_t hwcId = displayDevice->getHwcDisplayId();
3902 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3903 continue;
3904 }
3905
3906 result.appendFormat("Display %d HWC layers:\n", hwcId);
3907 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003908 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003909 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003910 });
Dan Stozae22aec72016-08-01 13:20:59 -07003911 result.append("\n");
3912 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003913
3914 /*
3915 * Dump HWComposer state
3916 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003917 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003918 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003919 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003920 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003921 result.appendFormat(" h/w composer %s\n",
3922 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003923 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003924
3925 /*
3926 * Dump gralloc state
3927 */
3928 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3929 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003930
3931 /*
3932 * Dump VrFlinger state if in use.
3933 */
3934 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3935 result.append("VrFlinger state:\n");
3936 result.append(mVrFlinger->Dump().c_str());
3937 result.append("\n");
3938 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003939}
3940
Mathias Agopian13127d82013-03-05 17:47:11 -08003941const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003942SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003943 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003944 wp<IBinder> dpy;
3945 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3946 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3947 dpy = mDisplays.keyAt(i);
3948 break;
3949 }
3950 }
3951 if (dpy == NULL) {
3952 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3953 // Just use the primary display so we have something to return
3954 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3955 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003956 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003957}
3958
Keun young Park63f165f2012-08-31 10:53:36 -07003959bool SurfaceFlinger::startDdmConnection()
3960{
3961 void* libddmconnection_dso =
3962 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3963 if (!libddmconnection_dso) {
3964 return false;
3965 }
3966 void (*DdmConnection_start)(const char* name);
3967 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003968 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003969 if (!DdmConnection_start) {
3970 dlclose(libddmconnection_dso);
3971 return false;
3972 }
3973 (*DdmConnection_start)(getServiceName());
3974 return true;
3975}
3976
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003977status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003978 switch (code) {
3979 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003980 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003981 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003982 case CLEAR_ANIMATION_FRAME_STATS:
3983 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003984 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003985 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003986 {
3987 // codes that require permission check
3988 IPCThreadState* ipc = IPCThreadState::self();
3989 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003990 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003991 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003992 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003993 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003994 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003995 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003996 break;
3997 }
Robert Carr1db73f62016-12-21 12:58:51 -08003998 /*
3999 * Calling setTransactionState is safe, because you need to have been
4000 * granted a reference to Client* and Handle* to do anything with it.
4001 *
4002 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4003 */
4004 case SET_TRANSACTION_STATE:
4005 case CREATE_SCOPED_CONNECTION:
4006 {
4007 return OK;
4008 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004009 case CAPTURE_SCREEN:
4010 {
4011 // codes that require permission check
4012 IPCThreadState* ipc = IPCThreadState::self();
4013 const int pid = ipc->getCallingPid();
4014 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004015 if ((uid != AID_GRAPHICS) &&
4016 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004017 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004018 return PERMISSION_DENIED;
4019 }
4020 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004021 }
4022 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004023 return OK;
4024}
4025
4026status_t SurfaceFlinger::onTransact(
4027 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4028{
4029 status_t credentialCheck = CheckTransactCodeCredentials(code);
4030 if (credentialCheck != OK) {
4031 return credentialCheck;
4032 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004033
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004034 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4035 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004036 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004037 IPCThreadState* ipc = IPCThreadState::self();
4038 const int uid = ipc->getCallingUid();
4039 if (CC_UNLIKELY(uid != AID_SYSTEM
4040 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004041 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004042 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004043 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004044 return PERMISSION_DENIED;
4045 }
4046 int n;
4047 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004048 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004049 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004050 return NO_ERROR;
4051 case 1002: // SHOW_UPDATES
4052 n = data.readInt32();
4053 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004054 invalidateHwcGeometry();
4055 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004056 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004057 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004058 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004059 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004060 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004061 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004062 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004063 setTransactionFlags(
4064 eTransactionNeeded|
4065 eDisplayTransactionNeeded|
4066 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004067 return NO_ERROR;
4068 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004069 case 1006:{ // send empty update
4070 signalRefresh();
4071 return NO_ERROR;
4072 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004073 case 1008: // toggle use of hw composer
4074 n = data.readInt32();
4075 mDebugDisableHWC = n ? 1 : 0;
4076 invalidateHwcGeometry();
4077 repaintEverything();
4078 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004079 case 1009: // toggle use of transform hint
4080 n = data.readInt32();
4081 mDebugDisableTransformHint = n ? 1 : 0;
4082 invalidateHwcGeometry();
4083 repaintEverything();
4084 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004085 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004086 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004087 reply->writeInt32(0);
4088 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004089 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004090 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004091 return NO_ERROR;
4092 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004093 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004094 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004095 return NO_ERROR;
4096 }
4097 case 1014: {
4098 // daltonize
4099 n = data.readInt32();
4100 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004101 case 1:
4102 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4103 break;
4104 case 2:
4105 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4106 break;
4107 case 3:
4108 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4109 break;
4110 default:
4111 mDaltonizer.setType(ColorBlindnessType::None);
4112 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004113 }
4114 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004115 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004116 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004117 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004118 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004119 invalidateHwcGeometry();
4120 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004121 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004122 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004123 case 1015: {
4124 // apply a color matrix
4125 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004126 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004127 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004128 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004129 for (size_t j = 0; j < 4; j++) {
4130 mColorMatrix[i][j] = data.readFloat();
4131 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004132 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004133 } else {
4134 mColorMatrix = mat4();
4135 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004136
4137 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4138 // the division by w in the fragment shader
4139 float4 lastRow(transpose(mColorMatrix)[3]);
4140 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4141 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4142 }
4143
Alan Viverette9c5a3332013-09-12 20:04:35 -07004144 invalidateHwcGeometry();
4145 repaintEverything();
4146 return NO_ERROR;
4147 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004148 // This is an experimental interface
4149 // Needs to be shifted to proper binder interface when we productize
4150 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004151 n = data.readInt32();
4152 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004153 return NO_ERROR;
4154 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004155 case 1017: {
4156 n = data.readInt32();
4157 mForceFullDamage = static_cast<bool>(n);
4158 return NO_ERROR;
4159 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004160 case 1018: { // Modify Choreographer's phase offset
4161 n = data.readInt32();
4162 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4163 return NO_ERROR;
4164 }
4165 case 1019: { // Modify SurfaceFlinger's phase offset
4166 n = data.readInt32();
4167 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4168 return NO_ERROR;
4169 }
Irvel468051e2016-06-13 16:44:44 -07004170 case 1020: { // Layer updates interceptor
4171 n = data.readInt32();
4172 if (n) {
4173 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004174 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004175 }
4176 else{
4177 ALOGV("Interceptor disabled");
4178 mInterceptor.disable();
4179 }
4180 return NO_ERROR;
4181 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004182 case 1021: { // Disable HWC virtual displays
4183 n = data.readInt32();
4184 mUseHwcVirtualDisplays = !n;
4185 return NO_ERROR;
4186 }
Romain Guy0147a172017-06-01 13:53:56 -07004187 case 1022: { // Set saturation boost
4188 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4189
4190 invalidateHwcGeometry();
4191 repaintEverything();
4192 return NO_ERROR;
4193 }
Romain Guy54f154a2017-10-24 21:40:32 +01004194 case 1023: { // Set native mode
4195 mForceNativeColorMode = data.readInt32() == 1;
4196
4197 invalidateHwcGeometry();
4198 repaintEverything();
4199 return NO_ERROR;
4200 }
4201 case 1024: { // Is wide color gamut rendering/color management supported?
4202 reply->writeBool(hasWideColorDisplay);
4203 return NO_ERROR;
4204 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004205 }
4206 }
4207 return err;
4208}
4209
Steven Thomas6d8110b2017-08-31 18:24:21 -07004210void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004211 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004212 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004213}
4214
Steven Thomas6d8110b2017-08-31 18:24:21 -07004215void SurfaceFlinger::repaintEverything() {
4216 ConditionalLock _l(mStateLock,
4217 std::this_thread::get_id() != mMainThreadId);
4218 repaintEverythingLocked();
4219}
4220
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004221// Checks that the requested width and height are valid and updates them to the display dimensions
4222// if they are set to 0
4223static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4224 Transform::orientation_flags rotation,
4225 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4226 // get screen geometry
4227 uint32_t displayWidth = displayDevice->getWidth();
4228 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004229
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004230 if (rotation & Transform::ROT_90) {
4231 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004232 }
4233
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004234 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4235 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4236 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4237 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004238 }
4239
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004240 if (*requestedWidth == 0) {
4241 *requestedWidth = displayWidth;
4242 }
4243 if (*requestedHeight == 0) {
4244 *requestedHeight = displayHeight;
4245 }
4246
4247 return NO_ERROR;
4248}
4249
4250// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4251class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004252public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004253 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4254 ~WindowDisconnector() {
4255 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004256 }
4257
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004258private:
4259 ANativeWindow* mWindow;
4260 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004261};
4262
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004263static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4264 uint32_t requestedHeight, bool hasWideColorDisplay,
4265 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4266 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4267 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4268
4269 int err = 0;
4270 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4271 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4272 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4273 err |= native_window_set_usage(window, usage);
4274
4275 if (hasWideColorDisplay) {
4276 err |= native_window_set_buffers_data_space(window,
4277 renderEngineUsesWideColor
4278 ? HAL_DATASPACE_DISPLAY_P3
4279 : HAL_DATASPACE_V0_SRGB);
4280 }
4281
4282 if (err != NO_ERROR) {
4283 return BAD_VALUE;
4284 }
4285
4286 /* TODO: Once we have the sync framework everywhere this can use
4287 * server-side waits on the fence that dequeueBuffer returns.
4288 */
4289 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4290 if (err != NO_ERROR) {
4291 return err;
4292 }
4293
4294 return NO_ERROR;
4295}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004296
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004297status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4298 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004299 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004300 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004301 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004302 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004303
4304 if (CC_UNLIKELY(display == 0))
4305 return BAD_VALUE;
4306
4307 if (CC_UNLIKELY(producer == 0))
4308 return BAD_VALUE;
4309
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004310 // if we have secure windows on this display, never allow the screen capture
4311 // unless the producer interface is local (i.e.: we can take a screenshot for
4312 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004313 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004314
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004315 // Convert to surfaceflinger's internal rotation type.
4316 Transform::orientation_flags rotationFlags;
4317 switch (rotation) {
4318 case ISurfaceComposer::eRotateNone:
4319 rotationFlags = Transform::ROT_0;
4320 break;
4321 case ISurfaceComposer::eRotate90:
4322 rotationFlags = Transform::ROT_90;
4323 break;
4324 case ISurfaceComposer::eRotate180:
4325 rotationFlags = Transform::ROT_180;
4326 break;
4327 case ISurfaceComposer::eRotate270:
4328 rotationFlags = Transform::ROT_270;
4329 break;
4330 default:
4331 rotationFlags = Transform::ROT_0;
4332 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4333 break;
4334 }
4335
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004336 { // Autolock scope
4337 Mutex::Autolock lock(mStateLock);
4338 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4339 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004340 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004341
4342 // create a surface (because we're a producer, and we need to
4343 // dequeue/queue a buffer)
4344 sp<Surface> surface = new Surface(producer, false);
4345
4346 // Put the screenshot Surface into async mode so that
4347 // Layer::headFenceHasSignaled will always return true and we'll latch the
4348 // first buffer regardless of whether or not its acquire fence has
4349 // signaled. This is needed to avoid a race condition in the rotation
4350 // animation. See b/30209608
4351 surface->setAsyncMode(true);
4352
4353 ANativeWindow* window = surface.get();
4354
4355 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4356 if (result != NO_ERROR) {
4357 return result;
4358 }
4359 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4360
4361 ANativeWindowBuffer* buffer = nullptr;
Romain Guy54f154a2017-10-24 21:40:32 +01004362 result = getWindowBuffer(window, reqWidth, reqHeight,
4363 hasWideColorDisplay && !mForceNativeColorMode,
4364 getRenderEngine().usesWideColor(), &buffer);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004365 if (result != NO_ERROR) {
4366 return result;
4367 }
4368
4369 // This mutex protects syncFd and captureResult for communication of the return values from the
4370 // main thread back to this Binder thread
4371 std::mutex captureMutex;
4372 std::condition_variable captureCondition;
4373 std::unique_lock<std::mutex> captureLock(captureMutex);
4374 int syncFd = -1;
4375 std::optional<status_t> captureResult;
4376
4377 sp<LambdaMessage> message = new LambdaMessage([&]() {
4378 // If there is a refresh pending, bug out early and tell the binder thread to try again
4379 // after the refresh.
4380 if (mRefreshPending) {
4381 ATRACE_NAME("Skipping screenshot for now");
4382 std::unique_lock<std::mutex> captureLock(captureMutex);
4383 captureResult = std::make_optional<status_t>(EAGAIN);
4384 captureCondition.notify_one();
4385 return;
4386 }
4387
4388 status_t result = NO_ERROR;
4389 int fd = -1;
4390 {
4391 Mutex::Autolock _l(mStateLock);
4392 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4393 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4394 minLayerZ, maxLayerZ, useIdentityTransform,
4395 rotationFlags, isLocalScreenshot, &fd);
4396 }
4397
4398 {
4399 std::unique_lock<std::mutex> captureLock(captureMutex);
4400 syncFd = fd;
4401 captureResult = std::make_optional<status_t>(result);
4402 captureCondition.notify_one();
4403 }
4404 });
4405
4406 result = postMessageAsync(message);
4407 if (result == NO_ERROR) {
4408 captureCondition.wait(captureLock, [&]() { return captureResult; });
4409 while (*captureResult == EAGAIN) {
4410 captureResult.reset();
4411 result = postMessageAsync(message);
4412 if (result != NO_ERROR) {
4413 return result;
4414 }
4415 captureCondition.wait(captureLock, [&]() { return captureResult; });
4416 }
4417 result = *captureResult;
4418 }
4419
4420 if (result == NO_ERROR) {
4421 // queueBuffer takes ownership of syncFd
4422 result = window->queueBuffer(window, buffer, syncFd);
4423 }
4424
4425 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004426}
4427
Mathias Agopian180f10d2013-04-10 22:55:41 -07004428
4429void SurfaceFlinger::renderScreenImplLocked(
4430 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004431 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004432 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004433 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004434{
4435 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004436 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004437
4438 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004439 const int32_t hw_w = hw->getWidth();
4440 const int32_t hw_h = hw->getHeight();
4441 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004442 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004443
Dan Stozac1879002014-05-22 15:59:05 -07004444 // if a default or invalid sourceCrop is passed in, set reasonable values
4445 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4446 !sourceCrop.isValid()) {
4447 sourceCrop.setLeftTop(Point(0, 0));
4448 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4449 }
4450
4451 // ensure that sourceCrop is inside screen
4452 if (sourceCrop.left < 0) {
4453 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4454 }
Dan Stozabe31f442014-06-11 11:20:54 -07004455 if (sourceCrop.right > hw_w) {
4456 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004457 }
4458 if (sourceCrop.top < 0) {
4459 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4460 }
Dan Stozabe31f442014-06-11 11:20:54 -07004461 if (sourceCrop.bottom > hw_h) {
4462 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004463 }
4464
Romain Guy88d37dd2017-05-26 17:57:05 -07004465#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01004466 engine.setWideColor(hw->getWideColorSupport() && !mForceNativeColorMode);
4467 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE : hw->getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004468#endif
4469
Mathias Agopian180f10d2013-04-10 22:55:41 -07004470 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004471 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004472
4473 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004474 engine.setViewportAndProjection(
4475 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004476 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004477
4478 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004479 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004480
Robert Carr1f0a16a2016-10-24 16:27:39 -07004481 // We loop through the first level of layers without traversing,
4482 // as we need to interpret min/max layer Z in the top level Z space.
4483 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004484 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004485 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004486 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004487 const Layer::State& state(layer->getDrawingState());
4488 if (state.z < minLayerZ || state.z > maxLayerZ) {
4489 continue;
4490 }
Dan Stoza412903f2017-04-27 13:42:17 -07004491 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004492 if (!layer->isVisible()) {
4493 return;
4494 }
4495 if (filtering) layer->setFiltering(true);
4496 layer->draw(hw, useIdentityTransform);
4497 if (filtering) layer->setFiltering(false);
4498 });
4499 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004500
Mathias Agopian931bda12013-08-28 18:11:46 -07004501 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004502}
4503
Dan Stozaabcda352017-06-01 14:37:39 -07004504// A simple RAII class that holds an EGLImage and destroys it either:
4505// a) When the destroy() method is called
4506// b) When the object goes out of scope
4507class ImageHolder {
4508public:
4509 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4510 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004511
Dan Stozaabcda352017-06-01 14:37:39 -07004512 void destroy() {
4513 if (mImage != EGL_NO_IMAGE_KHR) {
4514 eglDestroyImageKHR(mDisplay, mImage);
4515 mImage = EGL_NO_IMAGE_KHR;
4516 }
4517 }
4518
4519private:
4520 const EGLDisplay mDisplay;
4521 EGLImageKHR mImage;
4522};
4523
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004524status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4525 ANativeWindowBuffer* buffer, Rect sourceCrop,
4526 uint32_t reqWidth, uint32_t reqHeight,
4527 int32_t minLayerZ, int32_t maxLayerZ,
4528 bool useIdentityTransform,
4529 Transform::orientation_flags rotation,
4530 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004531 ATRACE_CALL();
4532
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004533 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004534 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004535 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004536 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004537 (state.z < minLayerZ || state.z > maxLayerZ)) {
4538 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004539 }
Dan Stoza412903f2017-04-27 13:42:17 -07004540 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004541 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4542 layer->isSecure());
4543 });
4544 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004545
4546 if (!isLocalScreenshot && secureLayerIsVisible) {
4547 ALOGW("FB is protected: PERMISSION_DENIED");
4548 return PERMISSION_DENIED;
4549 }
4550
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004551 int syncFd = -1;
4552 // create an EGLImage from the buffer so we can later
4553 // turn it into a texture
4554 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4555 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4556 if (image == EGL_NO_IMAGE_KHR) {
4557 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004558 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004559
Dan Stozaabcda352017-06-01 14:37:39 -07004560 // This will automatically destroy the image if we return before calling its destroy method
4561 ImageHolder imageHolder(mEGLDisplay, image);
4562
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004563 // this binds the given EGLImage as a framebuffer for the
4564 // duration of this scope.
4565 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004566 if (imageBond.getStatus() != NO_ERROR) {
4567 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004568 return INVALID_OPERATION;
4569 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004570
Dan Stozaabcda352017-06-01 14:37:39 -07004571 // this will in fact render into our dequeued buffer
4572 // via an FBO, which means we didn't have to create
4573 // an EGLSurface and therefore we're not
4574 // dependent on the context's EGLConfig.
4575 renderScreenImplLocked(
4576 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4577 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004578
Dan Stozaabcda352017-06-01 14:37:39 -07004579 // Attempt to create a sync khr object that can produce a sync point. If that
4580 // isn't available, create a non-dupable sync object in the fallback path and
4581 // wait on it directly.
4582 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4583 if (!DEBUG_SCREENSHOTS) {
4584 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4585 // native fence fd will not be populated until flush() is done.
4586 getRenderEngine().flush();
4587 }
4588
4589 if (sync != EGL_NO_SYNC_KHR) {
4590 // get the sync fd
4591 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4592 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4593 ALOGW("captureScreen: failed to dup sync khr object");
4594 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004595 }
Dan Stozaabcda352017-06-01 14:37:39 -07004596 eglDestroySyncKHR(mEGLDisplay, sync);
4597 } else {
4598 // fallback path
4599 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004600 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004601 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4602 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4603 EGLint eglErr = eglGetError();
4604 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4605 ALOGW("captureScreen: fence wait timed out");
4606 } else {
4607 ALOGW_IF(eglErr != EGL_SUCCESS,
4608 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004609 }
4610 eglDestroySyncKHR(mEGLDisplay, sync);
4611 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004612 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004613 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004614 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004615 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004616
4617 if (DEBUG_SCREENSHOTS) {
4618 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4619 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4620 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4621 hw, minLayerZ, maxLayerZ);
4622 delete [] pixels;
4623 }
4624
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004625 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004626 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004627
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004628 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004629}
4630
Mathias Agopiand5556842013-09-19 17:08:37 -07004631void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004632 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004633 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004634 for (size_t y=0 ; y<h ; y++) {
4635 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4636 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004637 if (p[x] != 0xFF000000) return;
4638 }
4639 }
4640 ALOGE("*** we just took a black screenshot ***\n"
4641 "requested minz=%d, maxz=%d, layerStack=%d",
4642 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004643
Robert Carr2047fae2016-11-28 14:09:09 -08004644 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004645 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004646 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004647 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004648 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004649 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004650 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4651 layer->isVisible() ? '+' : '-',
4652 i, layer->getName().string(), layer->getLayerStack(), state.z,
chaviw13fdc492017-06-27 12:40:18 -07004653 layer->isVisible(), state.flags, static_cast<float>(state.color.a));
Robert Carr1f0a16a2016-10-24 16:27:39 -07004654 i++;
4655 });
4656 }
4657 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004658 }
4659}
4660
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004661// ---------------------------------------------------------------------------
4662
Dan Stoza412903f2017-04-27 13:42:17 -07004663void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4664 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004665}
4666
Dan Stoza412903f2017-04-27 13:42:17 -07004667void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4668 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004669}
4670
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004671}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004672
4673
4674#if defined(__gl_h_)
4675#error "don't include gl/gl.h in this file"
4676#endif
4677
4678#if defined(__gl2_h_)
4679#error "don't include gl2/gl2.h in this file"
4680#endif