blob: a38e3b38d011195f14ab0842108f3677d9c3b1d6 [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);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700573 if (mCallback) {
574 mCallback->onVSyncEvent(when);
575 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700576 }
577
578 virtual void setVSyncEnabled(bool) {}
579 virtual void setPhaseOffset(nsecs_t) {}
580
581private:
582 std::mutex mCallbackMutex; // Protects the following
583 sp<VSyncSource::Callback> mCallback;
584};
585
Wei Wangf9b05ee2017-07-19 20:59:39 -0700586// Do not call property_set on main thread which will be blocked by init
587// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700589 ALOGI( "SurfaceFlinger's main thread ready to run. "
590 "Initializing graphics H/W...");
591
Thierry Strudel2924d012017-08-14 15:19:37 -0700592 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900593
Steven Thomasb02664d2017-07-26 18:48:28 -0700594 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800595
Steven Thomasb02664d2017-07-26 18:48:28 -0700596 // initialize EGL for the default display
597 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
598 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800599
Steven Thomasb02664d2017-07-26 18:48:28 -0700600 // start the EventThread
601 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
602 vsyncPhaseOffsetNs, true, "app");
603 mEventThread = new EventThread(vsyncSrc, *this, false);
604 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
605 sfVsyncPhaseOffsetNs, true, "sf");
606 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
607 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800608
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
610 struct sched_param param = {0};
611 param.sched_priority = 2;
612 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
613 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
614 }
615 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
616 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800617 }
618
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 // Get a RenderEngine for the given display / config (can't fail)
620 mRenderEngine = RenderEngine::create(mEGLDisplay,
621 HAL_PIXEL_FORMAT_RGBA_8888,
622 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 // retrieve the EGL context that was selected/created
625 mEGLContext = mRenderEngine->getEGLContext();
626
627 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
628 "couldn't create EGLContext");
629
630 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
631 "Starting with vr flinger active is not currently supported.");
632 mHwc.reset(new HWComposer(mHwcServiceName));
633 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800634
Steven Thomas050b2c82017-03-06 11:45:16 -0800635 if (useVrFlinger) {
636 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700637 // This callback is called from the vr flinger dispatch thread. We
638 // need to call signalTransaction(), which requires holding
639 // mStateLock when we're not on the main thread. Acquiring
640 // mStateLock from the vr flinger dispatch thread might trigger a
641 // deadlock in surface flinger (see b/66916578), so post a message
642 // to be handled on the main thread instead.
643 sp<LambdaMessage> message = new LambdaMessage([=]() {
644 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
645 mVrFlingerRequestsDisplay = requestDisplay;
646 signalTransaction();
647 });
648 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800649 };
650 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
651 vrFlingerRequestDisplayCallback);
652 if (!mVrFlinger) {
653 ALOGE("Failed to start vrflinger");
654 }
655 }
656
Jamie Gennisd1700752013-10-14 12:22:52 -0700657 mEventControlThread = new EventControlThread(this);
658 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
659
Mathias Agopian92a979a2012-08-02 18:32:23 -0700660 // initialize our drawing state
661 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700662
Andy McFadden13a082e2012-08-24 10:16:42 -0700663 // set initial conditions (e.g. unblank default device)
664 initializeDisplays();
665
Dan Stoza4e637772016-07-28 13:31:51 -0700666 mRenderEngine->primeCache();
667
Wei Wangf9b05ee2017-07-19 20:59:39 -0700668 // Inform native graphics APIs whether the present timestamp is supported:
669 if (getHwComposer().hasCapability(
670 HWC2::Capability::PresentFenceIsNotReliable)) {
671 mStartPropertySetThread = new StartPropertySetThread(false);
672 } else {
673 mStartPropertySetThread = new StartPropertySetThread(true);
674 }
675
676 if (mStartPropertySetThread->Start() != NO_ERROR) {
677 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800678 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800679
Dan Stoza9e56aa02015-11-02 13:00:03 -0800680 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700681}
682
Romain Guy11d63f42017-07-20 12:47:14 -0700683void SurfaceFlinger::readPersistentProperties() {
684 char value[PROPERTY_VALUE_MAX];
685
686 property_get("persist.sys.sf.color_saturation", value, "1.0");
687 mSaturation = atof(value);
688 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100689
690 property_get("persist.sys.sf.native_mode", value, "0");
691 mForceNativeColorMode = atoi(value) == 1;
692 if (mForceNativeColorMode) {
693 ALOGV("Forcing native color mode");
694 }
Romain Guy11d63f42017-07-20 12:47:14 -0700695}
696
Mathias Agopiana67e4182012-06-19 17:26:12 -0700697void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800698 // Start boot animation service by setting a property mailbox
699 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700700 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800701 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700702 if (mStartPropertySetThread->join() != NO_ERROR) {
703 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800704 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700705}
706
Mathias Agopian875d8e12013-06-07 15:35:48 -0700707size_t SurfaceFlinger::getMaxTextureSize() const {
708 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700709}
710
Mathias Agopian875d8e12013-06-07 15:35:48 -0700711size_t SurfaceFlinger::getMaxViewportDims() const {
712 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700713}
714
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800715// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800716
Jamie Gennis582270d2011-08-17 18:19:00 -0700717bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800718 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800719 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800720 return authenticateSurfaceTextureLocked(bufferProducer);
721}
722
723bool SurfaceFlinger::authenticateSurfaceTextureLocked(
724 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800725 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700726 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800727}
728
Brian Anderson6b376712017-04-04 10:51:39 -0700729status_t SurfaceFlinger::getSupportedFrameTimestamps(
730 std::vector<FrameEvent>* outSupported) const {
731 *outSupported = {
732 FrameEvent::REQUESTED_PRESENT,
733 FrameEvent::ACQUIRE,
734 FrameEvent::LATCH,
735 FrameEvent::FIRST_REFRESH_START,
736 FrameEvent::LAST_REFRESH_START,
737 FrameEvent::GPU_COMPOSITION_DONE,
738 FrameEvent::DEQUEUE_READY,
739 FrameEvent::RELEASE,
740 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700741 ConditionalLock _l(mStateLock,
742 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700743 if (!getHwComposer().hasCapability(
744 HWC2::Capability::PresentFenceIsNotReliable)) {
745 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
746 }
747 return NO_ERROR;
748}
749
Dan Stoza7f7da322014-05-02 15:26:25 -0700750status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
751 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700752 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700753 return BAD_VALUE;
754 }
755
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500756 if (!display.get())
757 return NAME_NOT_FOUND;
758
Jesse Hall692c7232012-11-08 15:41:56 -0800759 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700760 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800761 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700762 type = i;
763 break;
764 }
765 }
766
767 if (type < 0) {
768 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700769 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700770
Mathias Agopian8b736f12012-08-13 17:54:26 -0700771 // TODO: Not sure if display density should handled by SF any longer
772 class Density {
773 static int getDensityFromProperty(char const* propName) {
774 char property[PROPERTY_VALUE_MAX];
775 int density = 0;
776 if (property_get(propName, property, NULL) > 0) {
777 density = atoi(property);
778 }
779 return density;
780 }
781 public:
782 static int getEmuDensity() {
783 return getDensityFromProperty("qemu.sf.lcd_density"); }
784 static int getBuildDensity() {
785 return getDensityFromProperty("ro.sf.lcd_density"); }
786 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700787
Dan Stoza7f7da322014-05-02 15:26:25 -0700788 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700789
Steven Thomas6d8110b2017-08-31 18:24:21 -0700790 ConditionalLock _l(mStateLock,
791 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800792 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700793 DisplayInfo info = DisplayInfo();
794
Dan Stoza9e56aa02015-11-02 13:00:03 -0800795 float xdpi = hwConfig->getDpiX();
796 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700797
798 if (type == DisplayDevice::DISPLAY_PRIMARY) {
799 // The density of the device is provided by a build property
800 float density = Density::getBuildDensity() / 160.0f;
801 if (density == 0) {
802 // the build doesn't provide a density -- this is wrong!
803 // use xdpi instead
804 ALOGE("ro.sf.lcd_density must be defined as a build property");
805 density = xdpi / 160.0f;
806 }
807 if (Density::getEmuDensity()) {
808 // if "qemu.sf.lcd_density" is specified, it overrides everything
809 xdpi = ydpi = density = Density::getEmuDensity();
810 density /= 160.0f;
811 }
812 info.density = density;
813
814 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700815 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000816 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700817 } else {
818 // TODO: where should this value come from?
819 static const int TV_DENSITY = 213;
820 info.density = TV_DENSITY / 160.0f;
821 info.orientation = 0;
822 }
823
Dan Stoza9e56aa02015-11-02 13:00:03 -0800824 info.w = hwConfig->getWidth();
825 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700826 info.xdpi = xdpi;
827 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900829 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830
Andy McFadden91b2ca82014-06-13 14:04:23 -0700831 // This is how far in advance a buffer must be queued for
832 // presentation at a given time. If you want a buffer to appear
833 // on the screen at time N, you must submit the buffer before
834 // (N - presentationDeadline).
835 //
836 // Normally it's one full refresh period (to give SF a chance to
837 // latch the buffer), but this can be reduced by configuring a
838 // DispSync offset. Any additional delays introduced by the hardware
839 // composer or panel must be accounted for here.
840 //
841 // We add an additional 1ms to allow for processing time and
842 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800843 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800844 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700845
846 // All non-virtual displays are currently considered secure.
847 info.secure = true;
848
Michael Wright28f24d02016-07-12 13:30:53 -0700849 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850 }
851
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 return NO_ERROR;
853}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700854
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800855status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700856 DisplayStatInfo* stats) {
857 if (stats == NULL) {
858 return BAD_VALUE;
859 }
860
861 // FIXME for now we always return stats for the primary display
862 memset(stats, 0, sizeof(*stats));
863 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
864 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
865 return NO_ERROR;
866}
867
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700868int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800869 if (display == NULL) {
870 ALOGE("%s : display is NULL", __func__);
871 return BAD_VALUE;
872 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700873
874 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700875 if (device != NULL) {
876 return device->getActiveConfig();
877 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700878
Dan Stoza24a42e92015-03-09 10:04:11 -0700879 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700880}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700881
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700882void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
883 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
884 this);
885 int32_t type = hw->getDisplayType();
886 int currentMode = hw->getActiveConfig();
887
888 if (mode == currentMode) {
889 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
890 return;
891 }
892
893 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
894 ALOGW("Trying to set config for virtual display");
895 return;
896 }
897
898 hw->setActiveConfig(mode);
899 getHwComposer().setActiveConfig(type, mode);
900}
901
902status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
903 class MessageSetActiveConfig: public MessageBase {
904 SurfaceFlinger& mFlinger;
905 sp<IBinder> mDisplay;
906 int mMode;
907 public:
908 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
909 int mode) :
910 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
911 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700912 Vector<DisplayInfo> configs;
913 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700914 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700915 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700916 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700917 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700918 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700919 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
920 if (hw == NULL) {
921 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700922 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700923 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
924 ALOGW("Attempt to set active config = %d for virtual display",
925 mMode);
926 } else {
927 mFlinger.setActiveConfigInternal(hw, mMode);
928 }
929 return true;
930 }
931 };
932 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
933 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700934 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700935}
Michael Wright28f24d02016-07-12 13:30:53 -0700936status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
937 Vector<android_color_mode_t>* outColorModes) {
938 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
939 return BAD_VALUE;
940 }
941
942 if (!display.get()) {
943 return NAME_NOT_FOUND;
944 }
945
946 int32_t type = NAME_NOT_FOUND;
947 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
948 if (display == mBuiltinDisplays[i]) {
949 type = i;
950 break;
951 }
952 }
953
954 if (type < 0) {
955 return type;
956 }
957
Steven Thomas6d8110b2017-08-31 18:24:21 -0700958 std::vector<android_color_mode_t> modes;
959 {
960 ConditionalLock _l(mStateLock,
961 std::this_thread::get_id() != mMainThreadId);
962 modes = getHwComposer().getColorModes(type);
963 }
Michael Wright28f24d02016-07-12 13:30:53 -0700964 outColorModes->clear();
965 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
966
967 return NO_ERROR;
968}
969
970android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700971 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700972 if (device != nullptr) {
973 return device->getActiveColorMode();
974 }
975 return static_cast<android_color_mode_t>(BAD_VALUE);
976}
977
978void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
979 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700980 int32_t type = hw->getDisplayType();
981 android_color_mode_t currentMode = hw->getActiveColorMode();
982
983 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700984 return;
985 }
986
987 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
988 ALOGW("Trying to set config for virtual display");
989 return;
990 }
991
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600992 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
993 hw->getDisplayType());
994
Michael Wright28f24d02016-07-12 13:30:53 -0700995 hw->setActiveColorMode(mode);
996 getHwComposer().setActiveColorMode(type, mode);
997}
998
999
1000status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
1001 android_color_mode_t colorMode) {
1002 class MessageSetActiveColorMode: public MessageBase {
1003 SurfaceFlinger& mFlinger;
1004 sp<IBinder> mDisplay;
1005 android_color_mode_t mMode;
1006 public:
1007 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1008 android_color_mode_t mode) :
1009 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1010 virtual bool handler() {
1011 Vector<android_color_mode_t> modes;
1012 mFlinger.getDisplayColorModes(mDisplay, &modes);
1013 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1014 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001015 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1016 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001017 return true;
1018 }
1019 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1020 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001021 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1022 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001023 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001024 ALOGW("Attempt to set active color mode %s %d for virtual display",
1025 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001026 } else {
1027 mFlinger.setActiveColorModeInternal(hw, mMode);
1028 }
1029 return true;
1030 }
1031 };
1032 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1033 postMessageSync(msg);
1034 return NO_ERROR;
1035}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001036
Svetoslavd85084b2014-03-20 10:28:31 -07001037status_t SurfaceFlinger::clearAnimationFrameStats() {
1038 Mutex::Autolock _l(mStateLock);
1039 mAnimFrameTracker.clearStats();
1040 return NO_ERROR;
1041}
1042
1043status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1044 Mutex::Autolock _l(mStateLock);
1045 mAnimFrameTracker.getStats(outStats);
1046 return NO_ERROR;
1047}
1048
Dan Stozac4f471e2016-03-24 09:31:08 -07001049status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1050 HdrCapabilities* outCapabilities) const {
1051 Mutex::Autolock _l(mStateLock);
1052
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001053 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001054 if (displayDevice == nullptr) {
1055 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1056 return BAD_VALUE;
1057 }
1058
1059 std::unique_ptr<HdrCapabilities> capabilities =
1060 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1061 if (capabilities) {
1062 std::swap(*outCapabilities, *capabilities);
1063 } else {
1064 return BAD_VALUE;
1065 }
1066
1067 return NO_ERROR;
1068}
1069
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001070status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001071 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1072 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001073
Chia-I Wu90f669f2017-10-05 14:24:41 -07001074 if (mInjectVSyncs == enable) {
1075 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001076 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001077
1078 if (enable) {
1079 ALOGV("VSync Injections enabled");
1080 if (mVSyncInjector.get() == nullptr) {
1081 mVSyncInjector = new InjectVSyncSource();
1082 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1083 }
1084 mEventQueue.setEventThread(mInjectorEventThread);
1085 } else {
1086 ALOGV("VSync Injections disabled");
1087 mEventQueue.setEventThread(mSFEventThread);
1088 }
1089
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001090 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001091 });
1092 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001093 return NO_ERROR;
1094}
1095
1096status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001097 Mutex::Autolock _l(mStateLock);
1098
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001099 if (!mInjectVSyncs) {
1100 ALOGE("VSync Injections not enabled");
1101 return BAD_VALUE;
1102 }
1103 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1104 ALOGV("Injecting VSync inside SurfaceFlinger");
1105 mVSyncInjector->onInjectSyncEvent(when);
1106 }
1107 return NO_ERROR;
1108}
1109
Kalle Raitaa099a242017-01-11 11:17:29 -08001110status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1111 IPCThreadState* ipc = IPCThreadState::self();
1112 const int pid = ipc->getCallingPid();
1113 const int uid = ipc->getCallingUid();
1114 if ((uid != AID_SHELL) &&
1115 !PermissionCache::checkPermission(sDump, pid, uid)) {
1116 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1117 return PERMISSION_DENIED;
1118 }
1119
1120 // Try to acquire a lock for 1s, fail gracefully
1121 const status_t err = mStateLock.timedLock(s2ns(1));
1122 const bool locked = (err == NO_ERROR);
1123 if (!locked) {
1124 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1125 return TIMED_OUT;
1126 }
1127
1128 outLayers->clear();
1129 mCurrentState.traverseInZOrder([&](Layer* layer) {
1130 outLayers->push_back(layer->getLayerDebugInfo());
1131 });
1132
1133 mStateLock.unlock();
1134 return NO_ERROR;
1135}
1136
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001137// ----------------------------------------------------------------------------
1138
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001139sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1140 ISurfaceComposer::VsyncSource vsyncSource) {
1141 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1142 return mSFEventThread->createEventConnection();
1143 } else {
1144 return mEventThread->createEventConnection();
1145 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001146}
1147
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001148// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001149
1150void SurfaceFlinger::waitForEvent() {
1151 mEventQueue.waitMessage();
1152}
1153
1154void SurfaceFlinger::signalTransaction() {
1155 mEventQueue.invalidate();
1156}
1157
1158void SurfaceFlinger::signalLayerUpdate() {
1159 mEventQueue.invalidate();
1160}
1161
1162void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001163 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001164 mEventQueue.refresh();
1165}
1166
1167status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001168 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001169 return mEventQueue.postMessage(msg, reltime);
1170}
1171
1172status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001173 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001174 status_t res = mEventQueue.postMessage(msg, reltime);
1175 if (res == NO_ERROR) {
1176 msg->wait();
1177 }
1178 return res;
1179}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001180
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001181void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001182 do {
1183 waitForEvent();
1184 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001185}
1186
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187void SurfaceFlinger::enableHardwareVsync() {
1188 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001189 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001190 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001191 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1192 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001193 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001194 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195}
1196
Jesse Hall948fe0c2013-10-14 12:56:09 -07001197void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001198 Mutex::Autolock _l(mHWVsyncLock);
1199
Jesse Hall948fe0c2013-10-14 12:56:09 -07001200 if (makeAvailable) {
1201 mHWVsyncAvailable = true;
1202 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001203 // Hardware vsync is not currently available, so abort the resync
1204 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001205 return;
1206 }
1207
Dan Stoza9e56aa02015-11-02 13:00:03 -08001208 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1209 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001210
1211 mPrimaryDispSync.reset();
1212 mPrimaryDispSync.setPeriod(period);
1213
1214 if (!mPrimaryHWVsyncEnabled) {
1215 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001216 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1217 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 mPrimaryHWVsyncEnabled = true;
1219 }
1220}
1221
Jesse Hall948fe0c2013-10-14 12:56:09 -07001222void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223 Mutex::Autolock _l(mHWVsyncLock);
1224 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001225 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1226 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001227 mPrimaryDispSync.endResync();
1228 mPrimaryHWVsyncEnabled = false;
1229 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001230 if (makeUnavailable) {
1231 mHWVsyncAvailable = false;
1232 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233}
1234
Tim Murray4a4e4a22016-04-19 16:29:23 +00001235void SurfaceFlinger::resyncWithRateLimit() {
1236 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001237
1238 // No explicit locking is needed here since EventThread holds a lock while calling this method
1239 static nsecs_t sLastResyncAttempted = 0;
1240 const nsecs_t now = systemTime();
1241 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001242 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001243 }
Dan Stoza57164302017-05-08 14:03:54 -07001244 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001245}
1246
Steven Thomasb02664d2017-07-26 18:48:28 -07001247void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1248 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001249 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001250 // Ignore any vsyncs from a previous hardware composer.
1251 if (sequenceId != mComposerSequenceId) {
1252 return;
1253 }
1254
1255 int32_t type;
1256 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001257 return;
1258 }
1259
Jamie Gennisd1700752013-10-14 12:22:52 -07001260 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261
Jamie Gennisd1700752013-10-14 12:22:52 -07001262 { // Scope for the lock
1263 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001264 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001265 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001266 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001267 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001268
1269 if (needsHwVsync) {
1270 enableHardwareVsync();
1271 } else {
1272 disableHardwareVsync(false);
1273 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001274}
1275
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001276void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001277 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001278 *compositorTiming = mCompositorTiming;
1279}
1280
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001281void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001282 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001283 wp<IBinder> token = mBuiltinDisplays[type];
1284
1285 // All non-virtual displays are currently considered secure.
1286 const bool isSecure = true;
1287
1288 sp<IGraphicBufferProducer> producer;
1289 sp<IGraphicBufferConsumer> consumer;
1290 BufferQueue::createBufferQueue(&producer, &consumer);
1291
1292 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1293
1294 bool hasWideColorModes = false;
1295 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1296 for (android_color_mode_t colorMode : modes) {
1297 switch (colorMode) {
1298 case HAL_COLOR_MODE_DISPLAY_P3:
1299 case HAL_COLOR_MODE_ADOBE_RGB:
1300 case HAL_COLOR_MODE_DCI_P3:
1301 hasWideColorModes = true;
1302 break;
1303 default:
1304 break;
1305 }
1306 }
Romain Guy54f154a2017-10-24 21:40:32 +01001307 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001308 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1309 token, fbs, producer, mRenderEngine->getEGLConfig(),
Romain Guy54f154a2017-10-24 21:40:32 +01001310 useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001311 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001312 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001313 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001314 defaultColorMode = HAL_COLOR_MODE_SRGB;
1315 }
1316 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001317 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001318
1319 // Add the primary display token to mDrawingState so we don't try to
1320 // recreate the DisplayDevice for the primary display.
1321 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1322
1323 // make the GLContext current so that we can create textures when creating
1324 // Layers (which may happens before we render something)
1325 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001326}
1327
Steven Thomasb02664d2017-07-26 18:48:28 -07001328void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1329 hwc2_display_t display, HWC2::Connection connection,
1330 bool primaryDisplay) {
1331 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1332 sequenceId, display,
1333 connection == HWC2::Connection::Connected ?
1334 "connected" : "disconnected",
1335 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001336
Steven Thomasb02664d2017-07-26 18:48:28 -07001337 // Only lock if we're not on the main thread. This function is normally
1338 // called on a hwbinder thread, but for the primary display it's called on
1339 // the main thread with the state lock already held, so don't attempt to
1340 // acquire it here.
1341 ConditionalLock lock(mStateLock,
1342 std::this_thread::get_id() != mMainThreadId);
1343
1344 if (primaryDisplay) {
1345 mHwc->onHotplug(display, connection);
1346 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1347 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001348 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001349 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001350 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001351 if (sequenceId != mComposerSequenceId) {
1352 return;
1353 }
1354 if (mHwc->isUsingVrComposer()) {
1355 ALOGE("External displays are not supported by the vr hardware composer.");
1356 return;
1357 }
1358 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001359 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001361 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001362 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001363 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1364 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001365 }
1366 setTransactionFlags(eDisplayTransactionNeeded);
1367
Andy McFadden9e9689c2012-10-10 18:17:51 -07001368 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001369 }
Mathias Agopian86303202012-07-24 22:46:10 -07001370}
1371
Steven Thomasb02664d2017-07-26 18:48:28 -07001372void SurfaceFlinger::onRefreshReceived(int sequenceId,
1373 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001374 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 if (sequenceId != mComposerSequenceId) {
1376 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001377 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001378 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001379}
1380
Dan Stoza9e56aa02015-11-02 13:00:03 -08001381void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001382 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001384 getHwComposer().setVsyncEnabled(disp,
1385 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001386}
1387
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001388// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001389void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001390 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001391 // Clear the drawing state so that the logic inside of
1392 // handleTransactionLocked will fire. It will determine the delta between
1393 // mCurrentState and mDrawingState and re-apply all changes when we make the
1394 // transition.
1395 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001397 mDisplays.clear();
1398}
1399
Steven Thomas050b2c82017-03-06 11:45:16 -08001400void SurfaceFlinger::updateVrFlinger() {
1401 if (!mVrFlinger)
1402 return;
1403 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1404 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001405 return;
1406 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001407
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1409 ALOGE("Vr flinger is only supported for remote hardware composer"
1410 " service connections. Ignoring request to transition to vr"
1411 " flinger.");
1412 mVrFlingerRequestsDisplay = false;
1413 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001414 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001415
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001416 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 int currentDisplayPowerMode = getDisplayDeviceLocked(
1419 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001420
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001422 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001424
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 resetDisplayState();
1426 mHwc.reset(); // Delete the current instance before creating the new one
1427 mHwc.reset(new HWComposer(
1428 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1429 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1432 "Switched to non-remote hardware composer");
1433
1434 if (vrFlingerRequestsDisplay) {
1435 mVrFlinger->GrantDisplayOwnership();
1436 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001437 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001438 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001439
1440 mVisibleRegionsDirty = true;
1441 invalidateHwcGeometry();
1442
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001443 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1445 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1446 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001447
Steven Thomasb02664d2017-07-26 18:48:28 -07001448 // Reset the timing values to account for the period of the swapped in HWC
1449 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1450 const nsecs_t period = activeConfig->getVsyncPeriod();
1451 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001452
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 // Use phase of 0 since phase is not known.
1454 // Use latency of 0, which will snap to the ideal latency.
1455 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001456
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001457 android_atomic_or(1, &mRepaintEverything);
1458 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001459}
1460
Mathias Agopian4fec8732012-06-29 14:12:52 -07001461void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001462 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001463 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001464 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001465 bool frameMissed = !mHadClientComposition &&
1466 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001467 (mPreviousPresentFence->getSignalTime() ==
1468 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001469 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001470 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001471 signalLayerUpdate();
1472 break;
1473 }
1474
Steven Thomas050b2c82017-03-06 11:45:16 -08001475 // Now that we're going to make it to the handleMessageTransaction()
1476 // call below it's safe to call updateVrFlinger(), which will
1477 // potentially trigger a display handoff.
1478 updateVrFlinger();
1479
Dan Stoza6b9454d2014-11-07 16:00:59 -08001480 bool refreshNeeded = handleMessageTransaction();
1481 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001482 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001483 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001484 // Signal a refresh if a transaction modified the window state,
1485 // a new buffer was latched, or if HWC has requested a full
1486 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001487 signalRefresh();
1488 }
1489 break;
1490 }
1491 case MessageQueue::REFRESH: {
1492 handleMessageRefresh();
1493 break;
1494 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001495 }
1496}
1497
Dan Stoza6b9454d2014-11-07 16:00:59 -08001498bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001499 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001500 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001501 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001502 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001503 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001505}
1506
Dan Stoza6b9454d2014-11-07 16:00:59 -08001507bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001508 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001509 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001510}
1511
1512void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001514
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001515 mRefreshPending = false;
1516
Pablo Ceballos40845df2016-01-25 17:41:15 -08001517 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001518
Brian Andersond6927fb2016-07-23 23:37:30 -07001519 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001520 rebuildLayerStacks();
1521 setUpHWComposer();
1522 doDebugFlashRegions();
1523 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001524 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001525
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001526 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001527
1528 mHadClientComposition = false;
1529 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1530 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1531 mHadClientComposition = mHadClientComposition ||
1532 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1533 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001534
Dan Stoza9e56aa02015-11-02 13:00:03 -08001535 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001536}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001537
Mathias Agopiancd60f992012-08-16 16:28:27 -07001538void SurfaceFlinger::doDebugFlashRegions()
1539{
1540 // is debugging enabled
1541 if (CC_LIKELY(!mDebugRegion))
1542 return;
1543
1544 const bool repaintEverything = mRepaintEverything;
1545 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1546 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001547 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001548 // transform the dirty region into this screen's coordinate space
1549 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1550 if (!dirtyRegion.isEmpty()) {
1551 // redraw the whole screen
1552 doComposeSurfaces(hw, Region(hw->bounds()));
1553
1554 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001556 RenderEngine& engine(getRenderEngine());
1557 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1558
Mathias Agopianda27af92012-09-13 18:17:13 -07001559 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560 }
1561 }
1562 }
1563
1564 postFramebuffer();
1565
1566 if (mDebugRegion > 1) {
1567 usleep(mDebugRegion * 1000);
1568 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001569
Dan Stoza9e56aa02015-11-02 13:00:03 -08001570 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001571 auto& displayDevice = mDisplays[displayId];
1572 if (!displayDevice->isDisplayOn()) {
1573 continue;
1574 }
1575
1576 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001577 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1578 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001579 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001580}
1581
Brian Andersond6927fb2016-07-23 23:37:30 -07001582void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001583{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001584 ATRACE_CALL();
1585 ALOGV("preComposition");
1586
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001588 mDrawingState.traverseInZOrder([&](Layer* layer) {
1589 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001590 needExtraInvalidate = true;
1591 }
Robert Carr2047fae2016-11-28 14:09:09 -08001592 });
1593
Mathias Agopiancd60f992012-08-16 16:28:27 -07001594 if (needExtraInvalidate) {
1595 signalLayerUpdate();
1596 }
1597}
1598
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001599void SurfaceFlinger::updateCompositorTiming(
1600 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1601 std::shared_ptr<FenceTime>& presentFenceTime) {
1602 // Update queue of past composite+present times and determine the
1603 // most recently known composite to present latency.
1604 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1605 nsecs_t compositeToPresentLatency = -1;
1606 while (!mCompositePresentTimes.empty()) {
1607 CompositePresentTime& cpt = mCompositePresentTimes.front();
1608 // Cached values should have been updated before calling this method,
1609 // which helps avoid duplicate syscalls.
1610 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1611 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1612 break;
1613 }
1614 compositeToPresentLatency = displayTime - cpt.composite;
1615 mCompositePresentTimes.pop();
1616 }
1617
1618 // Don't let mCompositePresentTimes grow unbounded, just in case.
1619 while (mCompositePresentTimes.size() > 16) {
1620 mCompositePresentTimes.pop();
1621 }
1622
Brian Andersond0010582017-03-07 13:20:31 -08001623 setCompositorTimingSnapped(
1624 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1625}
1626
1627void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1628 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001629 // Integer division and modulo round toward 0 not -inf, so we need to
1630 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001631 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001632 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1633 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1634
Brian Andersond0010582017-03-07 13:20:31 -08001635 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1636 if (idealLatency <= 0) {
1637 idealLatency = vsyncInterval;
1638 }
1639
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001640 // Snap the latency to a value that removes scheduling jitter from the
1641 // composition and present times, which often have >1ms of jitter.
1642 // Reducing jitter is important if an app attempts to extrapolate
1643 // something (such as user input) to an accurate diasplay time.
1644 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1645 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001646 nsecs_t bias = vsyncInterval / 2;
1647 int64_t extraVsyncs =
1648 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1649 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1650 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001651
Brian Andersond0010582017-03-07 13:20:31 -08001652 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1654 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001655 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656}
1657
1658void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001659{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001660 ATRACE_CALL();
1661 ALOGV("postComposition");
1662
Brian Anderson3546a3f2016-07-14 11:51:14 -07001663 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001664 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001665 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001666 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001667 }
1668
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001669 // |mStateLock| not needed as we are on the main thread
1670 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001671
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001672 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001673 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1674 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1675 glCompositionDoneFenceTime =
1676 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1677 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1678 } else {
1679 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1680 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001681
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001682 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001683 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1684 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1685 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001686
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001687 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1688 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1689
1690 // We use the refreshStartTime which might be sampled a little later than
1691 // when we started doing work for this frame, but that should be okay
1692 // since updateCompositorTiming has snapping logic.
1693 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001694 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001695 CompositorTiming compositorTiming;
1696 {
1697 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1698 compositorTiming = mCompositorTiming;
1699 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001700
Robert Carr2047fae2016-11-28 14:09:09 -08001701 mDrawingState.traverseInZOrder([&](Layer* layer) {
1702 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001703 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001704 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001705 recordBufferingStats(layer->getName().string(),
1706 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001707 }
Robert Carr2047fae2016-11-28 14:09:09 -08001708 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001709
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001710 if (presentFenceTime->isValid()) {
1711 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001712 enableHardwareVsync();
1713 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001714 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001715 }
1716 }
1717
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001718 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001719 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001720 enableHardwareVsync();
1721 }
1722 }
1723
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001724 if (mAnimCompositionPending) {
1725 mAnimCompositionPending = false;
1726
Brian Anderson4e606e32017-03-16 15:34:57 -07001727 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001728 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001729 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001730 } else {
1731 // The HWC doesn't support present fences, so use the refresh
1732 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001733 nsecs_t presentTime =
1734 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001735 mAnimFrameTracker.setActualPresentTime(presentTime);
1736 }
1737 mAnimFrameTracker.advanceFrame();
1738 }
Dan Stozab90cf072015-03-05 11:05:59 -08001739
1740 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1741 return;
1742 }
1743
1744 nsecs_t currentTime = systemTime();
1745 if (mHasPoweredOff) {
1746 mHasPoweredOff = false;
1747 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001748 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001749 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001750 if (numPeriods < NUM_BUCKETS - 1) {
1751 mFrameBuckets[numPeriods] += elapsedTime;
1752 } else {
1753 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1754 }
1755 mTotalTime += elapsedTime;
1756 }
1757 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001758}
1759
1760void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001761 ATRACE_CALL();
1762 ALOGV("rebuildLayerStacks");
1763
Mathias Agopiancd60f992012-08-16 16:28:27 -07001764 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001765 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001766 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001767 mVisibleRegionsDirty = false;
1768 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001769
Jeff Sharkey76488112017-02-27 14:15:18 -07001770 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1771 Region opaqueRegion;
1772 Region dirtyRegion;
1773 Vector<sp<Layer>> layersSortedByZ;
1774 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1775 const Transform& tr(displayDevice->getTransform());
1776 const Rect bounds(displayDevice->getBounds());
1777 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001778 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001779
Jeff Sharkey76488112017-02-27 14:15:18 -07001780 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001781 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1782 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001783 Region drawRegion(tr.transform(
1784 layer->visibleNonTransparentRegion));
1785 drawRegion.andSelf(bounds);
1786 if (!drawRegion.isEmpty()) {
1787 layersSortedByZ.add(layer);
1788 } else {
1789 // Clear out the HWC layer if this layer was
1790 // previously visible, but no longer is
Steven Thomasb02664d2017-07-26 18:48:28 -07001791 layer->destroyHwcLayer(
1792 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001793 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001794 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001795 // WM changes displayDevice->layerStack upon sleep/awake.
1796 // Here we make sure we delete the HWC layers even if
1797 // WM changed their layer stack.
Steven Thomasb02664d2017-07-26 18:48:28 -07001798 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001799 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001800 });
1801 }
1802 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1803 displayDevice->undefinedRegion.set(bounds);
1804 displayDevice->undefinedRegion.subtractSelf(
1805 tr.transform(opaqueRegion));
1806 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001807 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001808 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001809}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001810
Romain Guy0147a172017-06-01 13:53:56 -07001811mat4 SurfaceFlinger::computeSaturationMatrix() const {
1812 if (mSaturation == 1.0f) {
1813 return mat4();
1814 }
1815
1816 // Rec.709 luma coefficients
1817 float3 luminance{0.213f, 0.715f, 0.072f};
1818 luminance *= 1.0f - mSaturation;
1819 return mat4(
1820 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1821 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1822 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1823 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1824 );
1825}
1826
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001827// pickColorMode translates a given dataspace into the best available color mode.
1828// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001829android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001830 if (mForceNativeColorMode) {
1831 return HAL_COLOR_MODE_NATIVE;
1832 }
1833
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001834 switch (dataSpace) {
1835 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1836 // system expects.
1837 case HAL_DATASPACE_UNKNOWN:
1838 case HAL_DATASPACE_SRGB:
1839 case HAL_DATASPACE_V0_SRGB:
1840 return HAL_COLOR_MODE_SRGB;
1841 break;
1842
1843 case HAL_DATASPACE_DISPLAY_P3:
1844 return HAL_COLOR_MODE_DISPLAY_P3;
1845 break;
1846
1847 default:
1848 // TODO (courtneygo): Do we want to assert an error here?
1849 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1850 dataSpace);
1851 return HAL_COLOR_MODE_SRGB;
1852 break;
1853 }
1854}
1855
Romain Guy0147a172017-06-01 13:53:56 -07001856android_dataspace SurfaceFlinger::bestTargetDataSpace(
1857 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001858 // Only support sRGB and Display-P3 right now.
1859 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1860 return HAL_DATASPACE_DISPLAY_P3;
1861 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001862 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1863 return HAL_DATASPACE_DISPLAY_P3;
1864 }
1865 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1866 return HAL_DATASPACE_DISPLAY_P3;
1867 }
1868
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001869 return HAL_DATASPACE_V0_SRGB;
1870}
1871
Mathias Agopiancd60f992012-08-16 16:28:27 -07001872void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001873 ATRACE_CALL();
1874 ALOGV("setUpHWComposer");
1875
Jesse Hall028dc8f2013-08-20 16:35:32 -07001876 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001877 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1878 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1879 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1880
1881 // If nothing has changed (!dirty), don't recompose.
1882 // If something changed, but we don't currently have any visible layers,
1883 // and didn't when we last did a composition, then skip it this time.
1884 // The second rule does two things:
1885 // - When all layers are removed from a display, we'll emit one black
1886 // frame, then nothing more until we get new layers.
1887 // - When a display is created with a private layer stack, we won't
1888 // emit any black frames until a layer is added to the layer stack.
1889 bool mustRecompose = dirty && !(empty && wasEmpty);
1890
1891 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1892 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1893 mustRecompose ? "doing" : "skipping",
1894 dirty ? "+" : "-",
1895 empty ? "+" : "-",
1896 wasEmpty ? "+" : "-");
1897
Dan Stoza71433162014-02-04 16:22:36 -08001898 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001899
1900 if (mustRecompose) {
1901 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1902 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001903 }
1904
Dan Stoza9e56aa02015-11-02 13:00:03 -08001905 // build the h/w work list
1906 if (CC_UNLIKELY(mGeometryInvalid)) {
1907 mGeometryInvalid = false;
1908 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1909 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1910 const auto hwcId = displayDevice->getHwcDisplayId();
1911 if (hwcId >= 0) {
1912 const Vector<sp<Layer>>& currentLayers(
1913 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001914 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001915 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001916 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001917 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001918 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001919 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001920 }
1921 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001922
Robert Carrae060832016-11-28 10:51:00 -08001923 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001924 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001926 }
1927 }
1928 }
1929 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001930 }
Riley Andrews03414a12014-07-01 14:22:59 -07001931
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001932
Romain Guy0147a172017-06-01 13:53:56 -07001933 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001934
Dan Stoza9e56aa02015-11-02 13:00:03 -08001935 // Set the per-frame data
1936 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1937 auto& displayDevice = mDisplays[displayId];
1938 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001939
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 if (hwcId < 0) {
1941 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001942 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001943 if (colorMatrix != mPreviousColorMatrix) {
1944 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1945 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1946 "display %zd: %d", displayId, result);
1947 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001948 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1949 layer->setPerFrameData(displayDevice);
1950 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001951
1952 if (hasWideColorDisplay) {
1953 android_color_mode newColorMode;
1954 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1955
1956 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1957 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1958 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1959 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1960 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1961 }
1962 newColorMode = pickColorMode(newDataSpace);
1963
Thierry Strudel2924d012017-08-14 15:19:37 -07001964 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001965 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001966 }
1967
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001968 mPreviousColorMatrix = colorMatrix;
1969
Dan Stoza9e56aa02015-11-02 13:00:03 -08001970 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001971 auto& displayDevice = mDisplays[displayId];
1972 if (!displayDevice->isDisplayOn()) {
1973 continue;
1974 }
1975
1976 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001977 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1978 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001979 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001980}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001981
Mathias Agopiancd60f992012-08-16 16:28:27 -07001982void SurfaceFlinger::doComposition() {
1983 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 ALOGV("doComposition");
1985
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001986 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001987 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001988 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001989 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001990 // transform the dirty region into this screen's coordinate space
1991 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001992
1993 // repaint the framebuffer (if needed)
1994 doDisplayComposition(hw, dirtyRegion);
1995
Mathias Agopiancd60f992012-08-16 16:28:27 -07001996 hw->dirtyRegion.clear();
1997 hw->flip(hw->swapRegion);
1998 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001999 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002000 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002001 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002002}
2003
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002004void SurfaceFlinger::postFramebuffer()
2005{
Mathias Agopian841cde52012-03-01 15:44:37 -08002006 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002007 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002008
Mathias Agopiana44b0412011-10-16 18:46:35 -07002009 const nsecs_t now = systemTime();
2010 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002011
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2013 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002014 if (!displayDevice->isDisplayOn()) {
2015 continue;
2016 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 const auto hwcId = displayDevice->getHwcDisplayId();
2018 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002019 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002020 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002021 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002022 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002023 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2024 sp<Fence> releaseFence = Fence::NO_FENCE;
2025 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
2026 releaseFence = displayDevice->getClientTargetAcquireFence();
2027 } else {
2028 auto hwcLayer = layer->getHwcLayer(hwcId);
2029 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002030 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002031 layer->onLayerDisplayed(releaseFence);
2032 }
2033 if (hwcId >= 0) {
2034 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002035 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002036 }
2037
Mathias Agopiana44b0412011-10-16 18:46:35 -07002038 mLastSwapBufferTime = systemTime() - now;
2039 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002040
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002041 // |mStateLock| not needed as we are on the main thread
2042 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002043 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2044 logFrameStats();
2045 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002046}
2047
Mathias Agopian87baae12012-07-31 12:38:26 -07002048void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002049{
Mathias Agopian841cde52012-03-01 15:44:37 -08002050 ATRACE_CALL();
2051
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002052 // here we keep a copy of the drawing state (that is the state that's
2053 // going to be overwritten by handleTransactionLocked()) outside of
2054 // mStateLock so that the side-effects of the State assignment
2055 // don't happen with mStateLock held (which can cause deadlocks).
2056 State drawingState(mDrawingState);
2057
Mathias Agopianca4d3602011-05-19 15:38:14 -07002058 Mutex::Autolock _l(mStateLock);
2059 const nsecs_t now = systemTime();
2060 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002061
Mathias Agopianca4d3602011-05-19 15:38:14 -07002062 // Here we're guaranteed that some transaction flags are set
2063 // so we can call handleTransactionLocked() unconditionally.
2064 // We call getTransactionFlags(), which will also clear the flags,
2065 // with mStateLock held to guarantee that mCurrentState won't change
2066 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002067
Mathias Agopiane57f2922012-08-09 16:29:12 -07002068 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002069 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002070
Mathias Agopianca4d3602011-05-19 15:38:14 -07002071 mLastTransactionTime = systemTime() - now;
2072 mDebugInTransaction = 0;
2073 invalidateHwcGeometry();
2074 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002075}
2076
Mathias Agopian87baae12012-07-31 12:38:26 -07002077void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002078{
Dan Stoza7dde5992015-05-22 09:51:44 -07002079 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002080 mCurrentState.traverseInZOrder([](Layer* layer) {
2081 layer->notifyAvailableFrames();
2082 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002083
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002084 /*
2085 * Traversal of the children
2086 * (perform the transaction for each of them if needed)
2087 */
2088
Mathias Agopian3559b072012-08-15 13:46:03 -07002089 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002090 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002091 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002092 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093
2094 const uint32_t flags = layer->doTransaction(0);
2095 if (flags & Layer::eVisibleRegion)
2096 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002097 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002098 }
2099
2100 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002101 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002102 */
2103
Mathias Agopiane57f2922012-08-09 16:29:12 -07002104 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002105 // here we take advantage of Vector's copy-on-write semantics to
2106 // improve performance by skipping the transaction entirely when
2107 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002108 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2109 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002110 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002111 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002112 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002113 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002114
2115 // find the displays that were removed
2116 // (ie: in drawing state but not in current state)
2117 // also handle displays that changed
2118 // (ie: displays that are in both lists)
2119 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002120 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2121 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002122 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002123 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002124 // Call makeCurrent() on the primary display so we can
2125 // be sure that nothing associated with this display
2126 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002127 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002128 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002129 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002130 if (hw != NULL)
2131 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002132 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002133 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002134 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002135 } else {
2136 ALOGW("trying to remove the main display");
2137 }
2138 } else {
2139 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002140 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002141 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002142 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2143 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002144 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002145 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002146 // recreating the DisplayDevice, so we just remove it
2147 // from the drawing state, so that it get re-added
2148 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002149 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002150 if (hw != NULL)
2151 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002152 mDisplays.removeItem(display);
2153 mDrawingState.displays.removeItemsAt(i);
2154 dc--; i--;
2155 // at this point we must loop to the next item
2156 continue;
2157 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002158
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002159 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002160 if (disp != NULL) {
2161 if (state.layerStack != draw[i].layerStack) {
2162 disp->setLayerStack(state.layerStack);
2163 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002164 if ((state.orientation != draw[i].orientation)
2165 || (state.viewport != draw[i].viewport)
2166 || (state.frame != draw[i].frame))
2167 {
2168 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002169 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002170 }
Michael Lentine47e45402014-07-18 15:34:25 -07002171 if (state.width != draw[i].width || state.height != draw[i].height) {
2172 disp->setDisplaySize(state.width, state.height);
2173 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002174 }
2175 }
2176 }
2177
2178 // find displays that were added
2179 // (ie: in current state but not in drawing state)
2180 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002181 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002182 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002183
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002184 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002185 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002186 sp<IGraphicBufferProducer> bqProducer;
2187 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002188 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002189
Dan Stoza9e56aa02015-11-02 13:00:03 -08002190 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002191 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002192 // Virtual displays without a surface are dormant:
2193 // they have external state (layer stack, projection,
2194 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002195 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002196
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002197 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002198 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002199 int width = 0;
2200 int status = state.surface->query(
2201 NATIVE_WINDOW_WIDTH, &width);
2202 ALOGE_IF(status != NO_ERROR,
2203 "Unable to query width (%d)", status);
2204 int height = 0;
2205 status = state.surface->query(
2206 NATIVE_WINDOW_HEIGHT, &height);
2207 ALOGE_IF(status != NO_ERROR,
2208 "Unable to query height (%d)", status);
2209 int intFormat = 0;
2210 status = state.surface->query(
2211 NATIVE_WINDOW_FORMAT, &intFormat);
2212 ALOGE_IF(status != NO_ERROR,
2213 "Unable to query format (%d)", status);
2214 auto format = static_cast<android_pixel_format_t>(
2215 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002216
Dan Stoza8cf150a2016-08-02 10:27:31 -07002217 mHwc->allocateVirtualDisplay(width, height, &format,
2218 &hwcId);
2219 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002220
Dan Stoza5cf424b2016-05-20 14:02:39 -07002221 // TODO: Plumb requested format back up to consumer
2222
Dan Stoza9e56aa02015-11-02 13:00:03 -08002223 sp<VirtualDisplaySurface> vds =
2224 new VirtualDisplaySurface(*mHwc,
2225 hwcId, state.surface, bqProducer,
2226 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002227
2228 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002229 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002230 }
2231 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002232 ALOGE_IF(state.surface!=NULL,
2233 "adding a supported display, but rendering "
2234 "surface is provided (%p), ignoring it",
2235 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002236
2237 hwcId = state.type;
2238 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2239 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002240 }
2241
2242 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002243 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002244 sp<DisplayDevice> hw =
2245 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2246 dispSurface, producer,
2247 mRenderEngine->getEGLConfig(),
2248 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002249 hw->setLayerStack(state.layerStack);
2250 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002251 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002252 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002253 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002254 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002255 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002256 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002257 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002258 }
2259 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002260 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002261 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002262
Mathias Agopian84300952012-11-21 16:02:13 -08002263 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2264 // The transform hint might have changed for some layers
2265 // (either because a display has changed, or because a layer
2266 // as changed).
2267 //
2268 // Walk through all the layers in currentLayers,
2269 // and update their transform hint.
2270 //
2271 // If a layer is visible only on a single display, then that
2272 // display is used to calculate the hint, otherwise we use the
2273 // default display.
2274 //
2275 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2276 // the hint is set before we acquire a buffer from the surface texture.
2277 //
2278 // NOTE: layer transactions have taken place already, so we use their
2279 // drawing state. However, SurfaceFlinger's own transaction has not
2280 // happened yet, so we must use the current state layer list
2281 // (soon to become the drawing state list).
2282 //
2283 sp<const DisplayDevice> disp;
2284 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002285 bool first = true;
2286 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002287 // NOTE: we rely on the fact that layers are sorted by
2288 // layerStack first (so we don't have to traverse the list
2289 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002290 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002291 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002292 currentlayerStack = layerStack;
2293 // figure out if this layerstack is mirrored
2294 // (more than one display) if so, pick the default display,
2295 // if not, pick the only display it's on.
2296 disp.clear();
2297 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2298 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002299 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002300 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002301 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002302 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002303 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002304 break;
2305 }
2306 }
2307 }
2308 }
Chet Haase91d25932013-04-11 15:24:55 -07002309 if (disp == NULL) {
2310 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2311 // redraw after transform hint changes. See bug 8508397.
2312
2313 // could be null when this layer is using a layerStack
2314 // that is not visible on any display. Also can occur at
2315 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002316 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002317 }
Chet Haase91d25932013-04-11 15:24:55 -07002318 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002319
2320 first = false;
2321 });
Mathias Agopian84300952012-11-21 16:02:13 -08002322 }
2323
2324
Mathias Agopian3559b072012-08-15 13:46:03 -07002325 /*
2326 * Perform our own transaction if needed
2327 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002328
2329 if (mLayersAdded) {
2330 mLayersAdded = false;
2331 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002332 mVisibleRegionsDirty = true;
2333 }
2334
2335 // some layers might have been removed, so
2336 // we need to update the regions they're exposing.
2337 if (mLayersRemoved) {
2338 mLayersRemoved = false;
2339 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002340 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002341 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002342 // this layer is not visible anymore
2343 // TODO: we could traverse the tree from front to back and
2344 // compute the actual visible region
2345 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002346 Region visibleReg;
2347 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002348 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002349 }
Robert Carr2047fae2016-11-28 14:09:09 -08002350 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002351 }
2352
2353 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002354
2355 updateCursorAsync();
2356}
2357
2358void SurfaceFlinger::updateCursorAsync()
2359{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002360 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2361 auto& displayDevice = mDisplays[displayId];
2362 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002363 continue;
2364 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002365
2366 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2367 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002368 }
2369 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002370}
2371
2372void SurfaceFlinger::commitTransaction()
2373{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002374 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002375 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002376 for (const auto& l : mLayersPendingRemoval) {
2377 recordBufferingStats(l->getName().string(),
2378 l->getOccupancyHistory(true));
2379 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002380 }
2381 mLayersPendingRemoval.clear();
2382 }
2383
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002384 // If this transaction is part of a window animation then the next frame
2385 // we composite should be considered an animation as well.
2386 mAnimCompositionPending = mAnimTransactionPending;
2387
Mathias Agopian4fec8732012-06-29 14:12:52 -07002388 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002389 mDrawingState.traverseInZOrder([](Layer* layer) {
2390 layer->commitChildList();
2391 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002392 mTransactionPending = false;
2393 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002394 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002395}
2396
Chia-I Wuab0c3192017-08-01 11:29:00 -07002397void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002398 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002399{
Mathias Agopian841cde52012-03-01 15:44:37 -08002400 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002401 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002402
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002403 Region aboveOpaqueLayers;
2404 Region aboveCoveredLayers;
2405 Region dirty;
2406
Mathias Agopian87baae12012-07-31 12:38:26 -07002407 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002408
Robert Carr2047fae2016-11-28 14:09:09 -08002409 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002410 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002411 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002412
Jesse Hall01e29052013-02-19 16:13:35 -08002413 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002414 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002415 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002416
Mathias Agopianab028732010-03-16 16:41:46 -07002417 /*
2418 * opaqueRegion: area of a surface that is fully opaque.
2419 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002420 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002421
2422 /*
2423 * visibleRegion: area of a surface that is visible on screen
2424 * and not fully transparent. This is essentially the layer's
2425 * footprint minus the opaque regions above it.
2426 * Areas covered by a translucent surface are considered visible.
2427 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002428 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002429
2430 /*
2431 * coveredRegion: area of a surface that is covered by all
2432 * visible regions above it (which includes the translucent areas).
2433 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002434 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002435
Jesse Halla8026d22012-09-25 13:25:04 -07002436 /*
2437 * transparentRegion: area of a surface that is hinted to be completely
2438 * transparent. This is only used to tell when the layer has no visible
2439 * non-transparent regions and can be removed from the layer list. It
2440 * does not affect the visibleRegion of this layer or any layers
2441 * beneath it. The hint may not be correct if apps don't respect the
2442 * SurfaceView restrictions (which, sadly, some don't).
2443 */
2444 Region transparentRegion;
2445
Mathias Agopianab028732010-03-16 16:41:46 -07002446
2447 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002448 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002449 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002450 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002451 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002452 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002453 if (!visibleRegion.isEmpty()) {
2454 // Remove the transparent area from the visible region
2455 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002456 if (tr.preserveRects()) {
2457 // transform the transparent region
2458 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002459 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002460 // transformation too complex, can't do the
2461 // transparent region optimization.
2462 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002463 }
Mathias Agopianab028732010-03-16 16:41:46 -07002464 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465
Mathias Agopianab028732010-03-16 16:41:46 -07002466 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002467 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002468 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002469 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2470 // the opaque region is the layer's footprint
2471 opaqueRegion = visibleRegion;
2472 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473 }
2474 }
2475
Mathias Agopianab028732010-03-16 16:41:46 -07002476 // Clip the covered region to the visible region
2477 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2478
2479 // Update aboveCoveredLayers for next (lower) layer
2480 aboveCoveredLayers.orSelf(visibleRegion);
2481
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482 // subtract the opaque region covered by the layers above us
2483 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484
2485 // compute this layer's dirty region
2486 if (layer->contentDirty) {
2487 // we need to invalidate the whole region
2488 dirty = visibleRegion;
2489 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002490 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491 layer->contentDirty = false;
2492 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002493 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002494 * the exposed region consists of two components:
2495 * 1) what's VISIBLE now and was COVERED before
2496 * 2) what's EXPOSED now less what was EXPOSED before
2497 *
2498 * note that (1) is conservative, we start with the whole
2499 * visible region but only keep what used to be covered by
2500 * something -- which mean it may have been exposed.
2501 *
2502 * (2) handles areas that were not covered by anything but got
2503 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002504 */
Mathias Agopianab028732010-03-16 16:41:46 -07002505 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002506 const Region oldVisibleRegion = layer->visibleRegion;
2507 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002508 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2509 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510 }
2511 dirty.subtractSelf(aboveOpaqueLayers);
2512
2513 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002514 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515
Mathias Agopianab028732010-03-16 16:41:46 -07002516 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002518
Jesse Halla8026d22012-09-25 13:25:04 -07002519 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520 layer->setVisibleRegion(visibleRegion);
2521 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002522 layer->setVisibleNonTransparentRegion(
2523 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002524 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002525
Mathias Agopian87baae12012-07-31 12:38:26 -07002526 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002527}
2528
Chia-I Wuab0c3192017-08-01 11:29:00 -07002529void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002530 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002531 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002532 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002533 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002534 }
2535 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002536}
2537
Dan Stoza6b9454d2014-11-07 16:00:59 -08002538bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002540 ALOGV("handlePageFlip");
2541
Brian Andersond6927fb2016-07-23 23:37:30 -07002542 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543
Mathias Agopian4fec8732012-06-29 14:12:52 -07002544 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002545 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002546 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002547
2548 // Store the set of layers that need updates. This set must not change as
2549 // buffers are being latched, as this could result in a deadlock.
2550 // Example: Two producers share the same command stream and:
2551 // 1.) Layer 0 is latched
2552 // 2.) Layer 0 gets a new frame
2553 // 2.) Layer 1 gets a new frame
2554 // 3.) Layer 1 is latched.
2555 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2556 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002557 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002558 if (layer->hasQueuedFrame()) {
2559 frameQueued = true;
2560 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002561 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002562 } else {
2563 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002564 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002565 } else {
2566 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002567 }
Robert Carr2047fae2016-11-28 14:09:09 -08002568 });
2569
Dan Stoza9e56aa02015-11-02 13:00:03 -08002570 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002571 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002572 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002573 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002574 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002575 newDataLatched = true;
2576 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002577 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002578
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002579 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002580
2581 // If we will need to wake up at some time in the future to deal with a
2582 // queued frame that shouldn't be displayed during this vsync period, wake
2583 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002584 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002585 signalLayerUpdate();
2586 }
2587
2588 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002589 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590}
2591
Mathias Agopianad456f92011-01-13 17:53:01 -08002592void SurfaceFlinger::invalidateHwcGeometry()
2593{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002594 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002595}
2596
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002597
Fabien Sanglard830b8472016-11-30 16:35:58 -08002598void SurfaceFlinger::doDisplayComposition(
2599 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002600 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601{
Dan Stoza71433162014-02-04 16:22:36 -08002602 // We only need to actually compose the display if:
2603 // 1) It is being handled by hardware composer, which may need this to
2604 // keep its virtual display state machine in sync, or
2605 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002606 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002607 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002608 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002609 return;
2610 }
2611
Dan Stoza9e56aa02015-11-02 13:00:03 -08002612 ALOGV("doDisplayComposition");
2613
Mathias Agopian87baae12012-07-31 12:38:26 -07002614 Region dirtyRegion(inDirtyRegion);
2615
Mathias Agopianb8a55602009-06-26 19:06:36 -07002616 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002617 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618
Fabien Sanglard830b8472016-11-30 16:35:58 -08002619 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002620 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002621 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2622 // takes a rectangle, we must make sure to update that whole
2623 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002624 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002625 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002626 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002627 // We need to redraw the rectangle that will be updated
2628 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002629 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002630 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002631 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002632 } else {
2633 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002634 dirtyRegion.set(displayDevice->bounds());
2635 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636 }
2637 }
2638
Fabien Sanglard830b8472016-11-30 16:35:58 -08002639 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002641 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002642 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002643
2644 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002645 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646}
2647
Dan Stoza9e56aa02015-11-02 13:00:03 -08002648bool SurfaceFlinger::doComposeSurfaces(
2649 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002650{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002651 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002652
chaviwa76b2712017-09-20 12:02:26 -07002653 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002654 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002655
2656 mat4 oldColorMatrix;
2657 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2658 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2659 if (applyColorMatrix) {
2660 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2661 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2662 }
2663
Dan Stoza9e56aa02015-11-02 13:00:03 -08002664 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2665 if (hasClientComposition) {
2666 ALOGV("hasClientComposition");
2667
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002668#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01002669 mRenderEngine->setWideColor(
2670 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2671 mRenderEngine->setColorMode(mForceNativeColorMode ?
2672 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002673#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002674 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002675 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002676 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002677 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002678
2679 // |mStateLock| not needed as we are on the main thread
2680 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002681 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2682 }
2683 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002684 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002685
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002686 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002687 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2688 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002689 // when using overlays, we assume a fully transparent framebuffer
2690 // NOTE: we could reduce how much we need to clear, for instance
2691 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002692 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002693 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002694 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002695 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002696 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002697 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002698
2699 // we remove the scissor part
2700 // we're left with the letterbox region
2701 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002702 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002703
2704 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002705 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002706
2707 // but limit it to the dirty region
2708 region.andSelf(dirty);
2709
Mathias Agopianb9494d52012-04-18 02:28:45 -07002710 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002711 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002712 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002713 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002714 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002715 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002716
Dan Stoza9e56aa02015-11-02 13:00:03 -08002717 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002718 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002719 // scissor on the main display. It should never be needed
2720 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002721 const Rect& bounds(displayDevice->getBounds());
2722 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002723 if (scissor != bounds) {
2724 // scissor doesn't match the screen's dimensions, so we
2725 // need to clear everything outside of it and enable
2726 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002727
Mathias Agopianf45c5102012-10-24 16:29:17 -07002728 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002729 const uint32_t height = displayDevice->getHeight();
2730 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002731 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002732 }
2733 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002734 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002735
Mathias Agopian85d751c2012-08-29 16:59:24 -07002736 /*
2737 * and then, render the layers targeted at the framebuffer
2738 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002739
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 ALOGV("Rendering client layers");
2741 const Transform& displayTransform = displayDevice->getTransform();
2742 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002743 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002744 bool firstLayer = true;
2745 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2746 const Region clip(dirty.intersect(
2747 displayTransform.transform(layer->visibleRegion)));
2748 ALOGV("Layer: %s", layer->getName().string());
2749 ALOGV(" Composition type: %s",
2750 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002751 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 switch (layer->getCompositionType(hwcId)) {
2753 case HWC2::Composition::Cursor:
2754 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002755 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002756 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002757 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002758 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002759 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002760 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002761 // never clear the very first layer since we're
2762 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002763 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002764 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002765 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002766 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002767 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002768 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002769 break;
2770 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002772 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002773 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002774 } else {
2775 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002776 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002777 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002778 }
2779 } else {
2780 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002781 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002782 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002783 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002784 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002785 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002786 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002787 }
2788 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002789
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002790 if (applyColorMatrix) {
2791 getRenderEngine().setupColorTransform(oldColorMatrix);
2792 }
2793
Mathias Agopianf45c5102012-10-24 16:29:17 -07002794 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002795 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002796 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797}
2798
Fabien Sanglard830b8472016-11-30 16:35:58 -08002799void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2800 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002801 RenderEngine& engine(getRenderEngine());
2802 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803}
2804
Dan Stoza7d89d062015-04-30 13:29:25 -07002805status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002806 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002807 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002808 const sp<Layer>& lbc,
2809 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002810{
Dan Stoza7d89d062015-04-30 13:29:25 -07002811 // add this layer to the current state list
2812 {
2813 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002814 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002815 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2816 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002817 return NO_MEMORY;
2818 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002819 if (parent == nullptr) {
2820 mCurrentState.layersSortedByZ.add(lbc);
2821 } else {
chaviwc9674332017-08-28 12:32:18 -07002822 bool found = false;
2823 mCurrentState.traverseInZOrder([&](Layer* layer) {
2824 if (layer == parent.get()) {
2825 found = true;
2826 }
2827 });
2828
2829 if (!found) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002830 ALOGE("addClientLayer called with a removed parent");
2831 return NAME_NOT_FOUND;
2832 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002833 parent->addChild(lbc);
2834 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002835
Dan Stoza7d89d062015-04-30 13:29:25 -07002836 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002837 mLayersAdded = true;
2838 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002839 }
2840
Mathias Agopian96f08192010-06-02 23:28:45 -07002841 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002842 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002843
Dan Stoza7d89d062015-04-30 13:29:25 -07002844 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002845}
2846
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002847status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002848 Mutex::Autolock _l(mStateLock);
2849
Robert Carr1f0a16a2016-10-24 16:27:39 -07002850 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002851 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002852 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002853 if (topLevelOnly) {
2854 return NO_ERROR;
2855 }
2856
Chia-I Wu98f1c102017-05-30 14:54:08 -07002857 sp<Layer> ancestor = p;
2858 while (ancestor->getParent() != nullptr) {
2859 ancestor = ancestor->getParent();
2860 }
2861 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2862 ALOGE("removeLayer called with a layer whose parent has been removed");
2863 return NAME_NOT_FOUND;
2864 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002865
2866 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002867 } else {
2868 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002869 }
2870
Robert Carr136e2f62017-02-08 17:54:29 -08002871 // As a matter of normal operation, the LayerCleaner will produce a second
2872 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2873 // so we will succeed in promoting it, but it's already been removed
2874 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2875 // otherwise something has gone wrong and we are leaking the layer.
2876 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002877 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2878 layer->getName().string(),
2879 (p != nullptr) ? p->getName().string() : "no-parent");
2880 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002881 } else if (index < 0) {
2882 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002883 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002884
Chia-I Wuc6657022017-08-15 11:18:17 -07002885 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002886 mLayersPendingRemoval.add(layer);
2887 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002888 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002889 setTransactionFlags(eTransactionNeeded);
2890 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891}
2892
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002893uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002894 return android_atomic_release_load(&mTransactionFlags);
2895}
2896
Mathias Agopian3f844832013-08-07 21:24:32 -07002897uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2899}
2900
Mathias Agopian3f844832013-08-07 21:24:32 -07002901uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2903 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002904 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905 }
2906 return old;
2907}
2908
Mathias Agopian8b33f032012-07-24 20:43:54 -07002909void SurfaceFlinger::setTransactionState(
2910 const Vector<ComposerState>& state,
2911 const Vector<DisplayState>& displays,
2912 uint32_t flags)
2913{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002914 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002915 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002916 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002917
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002918 if (flags & eAnimation) {
2919 // For window updates that are part of an animation we must wait for
2920 // previous animation "frames" to be handled.
2921 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002922 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002923 if (CC_UNLIKELY(err != NO_ERROR)) {
2924 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002925 // caller after a few seconds.
2926 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2927 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002928 mAnimTransactionPending = false;
2929 break;
2930 }
2931 }
2932 }
2933
Mathias Agopiane57f2922012-08-09 16:29:12 -07002934 size_t count = displays.size();
2935 for (size_t i=0 ; i<count ; i++) {
2936 const DisplayState& s(displays[i]);
2937 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002938 }
2939
Mathias Agopiane57f2922012-08-09 16:29:12 -07002940 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002941 for (size_t i=0 ; i<count ; i++) {
2942 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002943 // Here we need to check that the interface we're given is indeed
2944 // one of our own. A malicious client could give us a NULL
2945 // IInterface, or one of its own or even one of our own but a
2946 // different type. All these situations would cause us to crash.
2947 //
2948 // NOTE: it would be better to use RTTI as we could directly check
2949 // that we have a Client*. however, RTTI is disabled in Android.
2950 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002951 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002952 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002953 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002954 sp<Client> client( static_cast<Client *>(s.client.get()) );
2955 transactionFlags |= setClientStateLocked(client, s.state);
2956 }
2957 }
2958 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002959 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002960
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002961 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2962 // anyway. This can be used as a flush mechanism for previous async transactions.
2963 // Empty animation transaction can be used to simulate back-pressure, so also force a
2964 // transaction for empty animation transactions.
2965 if (transactionFlags == 0 &&
2966 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002967 transactionFlags = eTransactionNeeded;
2968 }
2969
Mathias Agopian386aa982011-11-07 21:58:03 -08002970 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002971 if (mInterceptor.isEnabled()) {
2972 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2973 }
Irvel468051e2016-06-13 16:44:44 -07002974
Mathias Agopian386aa982011-11-07 21:58:03 -08002975 // this triggers the transaction
2976 setTransactionFlags(transactionFlags);
2977
2978 // if this is a synchronous transaction, wait for it to take effect
2979 // before returning.
2980 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002981 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002982 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002983 if (flags & eAnimation) {
2984 mAnimTransactionPending = true;
2985 }
2986 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002987 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2988 if (CC_UNLIKELY(err != NO_ERROR)) {
2989 // just in case something goes wrong in SF, return to the
2990 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002991 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2992 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002993 break;
2994 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002995 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996 }
2997}
2998
Mathias Agopiane57f2922012-08-09 16:29:12 -07002999uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3000{
Jesse Hall9a143922012-10-04 16:29:19 -07003001 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3002 if (dpyIdx < 0)
3003 return 0;
3004
Mathias Agopiane57f2922012-08-09 16:29:12 -07003005 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003006 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003007 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003008 const uint32_t what = s.what;
3009 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003010 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003011 disp.surface = s.surface;
3012 flags |= eDisplayTransactionNeeded;
3013 }
3014 }
3015 if (what & DisplayState::eLayerStackChanged) {
3016 if (disp.layerStack != s.layerStack) {
3017 disp.layerStack = s.layerStack;
3018 flags |= eDisplayTransactionNeeded;
3019 }
3020 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003021 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003022 if (disp.orientation != s.orientation) {
3023 disp.orientation = s.orientation;
3024 flags |= eDisplayTransactionNeeded;
3025 }
3026 if (disp.frame != s.frame) {
3027 disp.frame = s.frame;
3028 flags |= eDisplayTransactionNeeded;
3029 }
3030 if (disp.viewport != s.viewport) {
3031 disp.viewport = s.viewport;
3032 flags |= eDisplayTransactionNeeded;
3033 }
3034 }
Michael Lentine47e45402014-07-18 15:34:25 -07003035 if (what & DisplayState::eDisplaySizeChanged) {
3036 if (disp.width != s.width) {
3037 disp.width = s.width;
3038 flags |= eDisplayTransactionNeeded;
3039 }
3040 if (disp.height != s.height) {
3041 disp.height = s.height;
3042 flags |= eDisplayTransactionNeeded;
3043 }
3044 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003045 }
3046 return flags;
3047}
3048
3049uint32_t SurfaceFlinger::setClientStateLocked(
3050 const sp<Client>& client,
3051 const layer_state_t& s)
3052{
3053 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003054 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003055 if (layer != 0) {
3056 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003057 bool geometryAppliesWithResize =
3058 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003059 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003060 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003061 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003062 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003063 }
3064 if (what & layer_state_t::eLayerChanged) {
3065 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003066 const auto& p = layer->getParent();
3067 if (p == nullptr) {
3068 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3069 if (layer->setLayer(s.z) && idx >= 0) {
3070 mCurrentState.layersSortedByZ.removeAt(idx);
3071 mCurrentState.layersSortedByZ.add(layer);
3072 // we need traversal (state changed)
3073 // AND transaction (list changed)
3074 flags |= eTransactionNeeded|eTraversalNeeded;
3075 }
3076 } else {
3077 if (p->setChildLayer(layer, s.z)) {
3078 flags |= eTransactionNeeded|eTraversalNeeded;
3079 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003080 }
3081 }
Robert Carrdb66e622017-04-10 16:55:57 -07003082 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003083 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003084 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003085 mCurrentState.layersSortedByZ.removeAt(idx);
3086 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003087 flags |= eTransactionNeeded|eTraversalNeeded;
3088 }
3089 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003090 if (what & layer_state_t::eSizeChanged) {
3091 if (layer->setSize(s.w, s.h)) {
3092 flags |= eTraversalNeeded;
3093 }
3094 }
3095 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003096 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003097 flags |= eTraversalNeeded;
3098 }
chaviw13fdc492017-06-27 12:40:18 -07003099 if (what & layer_state_t::eColorChanged) {
3100 if (layer->setColor(s.color))
3101 flags |= eTraversalNeeded;
3102 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003103 if (what & layer_state_t::eMatrixChanged) {
3104 if (layer->setMatrix(s.matrix))
3105 flags |= eTraversalNeeded;
3106 }
3107 if (what & layer_state_t::eTransparentRegionChanged) {
3108 if (layer->setTransparentRegionHint(s.transparentRegion))
3109 flags |= eTraversalNeeded;
3110 }
Dan Stoza23116082015-06-18 14:58:39 -07003111 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003112 if (layer->setFlags(s.flags, s.mask))
3113 flags |= eTraversalNeeded;
3114 }
3115 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003116 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003117 flags |= eTraversalNeeded;
3118 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003119 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003120 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003121 flags |= eTraversalNeeded;
3122 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003123 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003124 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003125 // We only allow setting layer stacks for top level layers,
3126 // everything else inherits layer stack from its parent.
3127 if (layer->hasParent()) {
3128 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3129 layer->getName().string());
3130 } else if (idx < 0) {
3131 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3132 "that also does not appear in the top level layer list. Something"
3133 " has gone wrong.", layer->getName().string());
3134 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003135 mCurrentState.layersSortedByZ.removeAt(idx);
3136 mCurrentState.layersSortedByZ.add(layer);
3137 // we need traversal (state changed)
3138 // AND transaction (list changed)
3139 flags |= eTransactionNeeded|eTraversalNeeded;
3140 }
3141 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003142 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003143 if (s.barrierHandle != nullptr) {
3144 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3145 } else if (s.barrierGbp != nullptr) {
3146 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3147 if (authenticateSurfaceTextureLocked(gbp)) {
3148 const auto& otherLayer =
3149 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3150 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3151 } else {
3152 ALOGE("Attempt to defer transaction to to an"
3153 " unrecognized GraphicBufferProducer");
3154 }
3155 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003156 // We don't trigger a traversal here because if no other state is
3157 // changed, we don't want this to cause any more work
3158 }
chaviwf1961f72017-09-18 16:41:07 -07003159 if (what & layer_state_t::eReparent) {
3160 if (layer->reparent(s.parentHandleForChild)) {
chaviw06178942017-07-27 10:25:59 -07003161 flags |= eTransactionNeeded|eTraversalNeeded;
3162 }
3163 }
Robert Carr1db73f62016-12-21 12:58:51 -08003164 if (what & layer_state_t::eReparentChildren) {
3165 if (layer->reparentChildren(s.reparentHandle)) {
3166 flags |= eTransactionNeeded|eTraversalNeeded;
3167 }
3168 }
Robert Carr9524cb32017-02-13 11:32:32 -08003169 if (what & layer_state_t::eDetachChildren) {
3170 layer->detachChildren();
3171 }
Robert Carrc3574f72016-03-24 12:19:32 -07003172 if (what & layer_state_t::eOverrideScalingModeChanged) {
3173 layer->setOverrideScalingMode(s.overrideScalingMode);
3174 // We don't trigger a traversal here because if no other state is
3175 // changed, we don't want this to cause any more work
3176 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003177 }
3178 return flags;
3179}
3180
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003181status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003182 const String8& name,
3183 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003184 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003185 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3186 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003187{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003188 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003189 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003190 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003191 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003192 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003193
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003194 status_t result = NO_ERROR;
3195
3196 sp<Layer> layer;
3197
Cody Northropbc755282017-03-31 12:00:08 -06003198 String8 uniqueName = getUniqueLayerName(name);
3199
Mathias Agopian3165cc22012-08-08 19:42:09 -07003200 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3201 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003202 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003203 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003204 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003205 break;
chaviw13fdc492017-06-27 12:40:18 -07003206 case ISurfaceComposerClient::eFXSurfaceColor:
3207 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003208 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003209 handle, gbp, &layer);
3210 break;
3211 default:
3212 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003213 break;
3214 }
3215
Dan Stoza7d89d062015-04-30 13:29:25 -07003216 if (result != NO_ERROR) {
3217 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003218 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003219
Chia-I Wuab0c3192017-08-01 11:29:00 -07003220 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3221 // TODO b/64227542
3222 if (windowType == 441731) {
3223 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3224 layer->setPrimaryDisplayOnly();
3225 }
3226
Albert Chaulk479c60c2017-01-27 14:21:34 -05003227 layer->setInfo(windowType, ownerUid);
3228
Robert Carr1f0a16a2016-10-24 16:27:39 -07003229 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003230 if (result != NO_ERROR) {
3231 return result;
3232 }
Irvelffc9efc2016-07-27 15:16:37 -07003233 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003234
3235 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003236 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003237}
3238
Cody Northropbc755282017-03-31 12:00:08 -06003239String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3240{
3241 bool matchFound = true;
3242 uint32_t dupeCounter = 0;
3243
3244 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3245 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3246
3247 // Loop over layers until we're sure there is no matching name
3248 while (matchFound) {
3249 matchFound = false;
3250 mDrawingState.traverseInZOrder([&](Layer* layer) {
3251 if (layer->getName() == uniqueName) {
3252 matchFound = true;
3253 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3254 }
3255 });
3256 }
3257
3258 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3259
3260 return uniqueName;
3261}
3262
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003263status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3264 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3265 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003266{
3267 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003268 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003269 case PIXEL_FORMAT_TRANSPARENT:
3270 case PIXEL_FORMAT_TRANSLUCENT:
3271 format = PIXEL_FORMAT_RGBA_8888;
3272 break;
3273 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003274 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003275 break;
3276 }
3277
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003278 *outLayer = new Layer(this, client, name, w, h, flags);
3279 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3280 if (err == NO_ERROR) {
3281 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003282 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003284
3285 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3286 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003287}
3288
chaviw13fdc492017-06-27 12:40:18 -07003289status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003290 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3291 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003292{
chaviw13fdc492017-06-27 12:40:18 -07003293 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003294 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003295 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003296 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003297}
3298
Mathias Agopianac9fa422013-02-11 16:40:36 -08003299status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003300{
Robert Carr9524cb32017-02-13 11:32:32 -08003301 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003302 status_t err = NO_ERROR;
3303 sp<Layer> l(client->getLayerUser(handle));
3304 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003305 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003306 err = removeLayer(l);
3307 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3308 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003309 }
3310 return err;
3311}
3312
Mathias Agopian13127d82013-03-05 17:47:11 -08003313status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003314{
Mathias Agopian67106042013-03-14 19:18:13 -07003315 // called by ~LayerCleaner() when all references to the IBinder (handle)
3316 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003317 sp<Layer> l = layer.promote();
3318 if (l == nullptr) {
3319 // The layer has already been removed, carry on
3320 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003321 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003322 // If we have a parent, then we can continue to live as long as it does.
3323 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003324}
3325
Mathias Agopianb60314a2012-04-10 22:09:54 -07003326// ---------------------------------------------------------------------------
3327
Andy McFadden13a082e2012-08-24 10:16:42 -07003328void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003329 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003330 Vector<ComposerState> state;
3331 Vector<DisplayState> displays;
3332 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003333 d.what = DisplayState::eDisplayProjectionChanged |
3334 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003335 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003336 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003337 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003338 d.frame.makeInvalid();
3339 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003340 d.width = 0;
3341 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003342 displays.add(d);
3343 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003344 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3345 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003346
Dan Stoza9e56aa02015-11-02 13:00:03 -08003347 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3348 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003349 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003350
Brian Andersond0010582017-03-07 13:20:31 -08003351 // Use phase of 0 since phase is not known.
3352 // Use latency of 0, which will snap to the ideal latency.
3353 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003354}
3355
3356void SurfaceFlinger::initializeDisplays() {
3357 class MessageScreenInitialized : public MessageBase {
3358 SurfaceFlinger* flinger;
3359 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003360 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003361 virtual bool handler() {
3362 flinger->onInitializeDisplays();
3363 return true;
3364 }
3365 };
3366 sp<MessageBase> msg = new MessageScreenInitialized(this);
3367 postMessageAsync(msg); // we may be called from main thread, use async message
3368}
3369
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003370void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003371 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003372 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3373 this);
3374 int32_t type = hw->getDisplayType();
3375 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003376
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003377 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003378 return;
3379 }
3380
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003381 hw->setPowerMode(mode);
3382 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3383 ALOGW("Trying to set power mode for virtual display");
3384 return;
3385 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003386
Irvelffc9efc2016-07-27 15:16:37 -07003387 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003388 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003389 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3390 if (idx < 0) {
3391 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3392 return;
3393 }
3394 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3395 }
3396
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003397 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003398 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003399 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003400 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3401 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003402 // FIXME: eventthread only knows about the main display right now
3403 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003404 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003405 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003406
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003407 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003408 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003409 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003410
3411 struct sched_param param = {0};
3412 param.sched_priority = 1;
3413 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3414 ALOGW("Couldn't set SCHED_FIFO on display on");
3415 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003416 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003417 // Turn off the display
3418 struct sched_param param = {0};
3419 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3420 ALOGW("Couldn't set SCHED_OTHER on display off");
3421 }
3422
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003423 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003424 disableHardwareVsync(true); // also cancels any in-progress resync
3425
Mathias Agopiancde87a32012-09-13 14:09:01 -07003426 // FIXME: eventthread only knows about the main display right now
3427 mEventThread->onScreenReleased();
3428 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003429
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003430 getHwComposer().setPowerMode(type, mode);
3431 mVisibleRegionsDirty = true;
3432 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003433 } else if (mode == HWC_POWER_MODE_DOZE ||
3434 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003435 // Update display while dozing
3436 getHwComposer().setPowerMode(type, mode);
3437 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3438 // FIXME: eventthread only knows about the main display right now
3439 mEventThread->onScreenAcquired();
3440 resyncToHardwareVsync(true);
3441 }
3442 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3443 // Leave display going to doze
3444 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3445 disableHardwareVsync(true); // also cancels any in-progress resync
3446 // FIXME: eventthread only knows about the main display right now
3447 mEventThread->onScreenReleased();
3448 }
3449 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003450 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003451 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003452 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003453 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003454}
3455
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003456void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3457 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003458 SurfaceFlinger& mFlinger;
3459 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003460 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003461 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003462 MessageSetPowerMode(SurfaceFlinger& flinger,
3463 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3464 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003465 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003466 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003467 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003468 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003469 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003470 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003471 ALOGW("Attempt to set power mode = %d for virtual display",
3472 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003473 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003474 mFlinger.setPowerModeInternal(
3475 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003476 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003477 return true;
3478 }
3479 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003480 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003481 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003482}
3483
3484// ---------------------------------------------------------------------------
3485
Vishnu Nair6a408532017-10-24 09:11:27 -07003486status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003487 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003488
Mathias Agopianbd115332013-04-18 16:41:04 -07003489 IPCThreadState* ipc = IPCThreadState::self();
3490 const int pid = ipc->getCallingPid();
3491 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003492
Mathias Agopianbd115332013-04-18 16:41:04 -07003493 if ((uid != AID_SHELL) &&
3494 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003495 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003496 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003497 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003498 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003499 // (this would indicate SF is stuck, but we want to be able to
3500 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003501 status_t err = mStateLock.timedLock(s2ns(1));
3502 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003503 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003504 result.appendFormat(
3505 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3506 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003507 }
3508
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003509 bool dumpAll = true;
3510 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003511 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003512
3513 if (asProto) {
3514 LayersProto layersProto = dumpProtoInfo();
3515 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3516 dumpAll = false;
3517 }
3518
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003519 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003520 if ((index < numArgs) &&
3521 (args[index] == String16("--list"))) {
3522 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003523 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003524 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003525 }
3526
3527 if ((index < numArgs) &&
3528 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003529 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003530 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003531 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003532 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003533
3534 if ((index < numArgs) &&
3535 (args[index] == String16("--latency-clear"))) {
3536 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003537 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003538 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003539 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003540
3541 if ((index < numArgs) &&
3542 (args[index] == String16("--dispsync"))) {
3543 index++;
3544 mPrimaryDispSync.dump(result);
3545 dumpAll = false;
3546 }
Dan Stozab90cf072015-03-05 11:05:59 -08003547
3548 if ((index < numArgs) &&
3549 (args[index] == String16("--static-screen"))) {
3550 index++;
3551 dumpStaticScreenStats(result);
3552 dumpAll = false;
3553 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003554
3555 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003556 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003557 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003558 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003559 dumpAll = false;
3560 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003561
3562 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3563 index++;
3564 dumpWideColorInfo(result);
3565 dumpAll = false;
3566 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003567 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003568
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003569 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003570 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003571 }
3572
Mathias Agopian9795c422009-08-26 16:36:26 -07003573 if (locked) {
3574 mStateLock.unlock();
3575 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576 }
3577 write(fd, result.string(), result.size());
3578 return NO_ERROR;
3579}
3580
Dan Stozac7014012014-02-14 15:03:43 -08003581void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3582 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003583{
Robert Carr2047fae2016-11-28 14:09:09 -08003584 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003585 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003586 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003587}
3588
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003589void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003590 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003591{
3592 String8 name;
3593 if (index < args.size()) {
3594 name = String8(args[index]);
3595 index++;
3596 }
3597
Dan Stoza9e56aa02015-11-02 13:00:03 -08003598 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3599 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003600 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003601
3602 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003603 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003604 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003605 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003606 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003607 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003608 }
Robert Carr2047fae2016-11-28 14:09:09 -08003609 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003610 }
3611}
3612
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003613void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003614 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003615{
3616 String8 name;
3617 if (index < args.size()) {
3618 name = String8(args[index]);
3619 index++;
3620 }
3621
Robert Carr2047fae2016-11-28 14:09:09 -08003622 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003623 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003624 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003625 }
Robert Carr2047fae2016-11-28 14:09:09 -08003626 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003627
Svetoslavd85084b2014-03-20 10:28:31 -07003628 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003629}
3630
Jamie Gennis6547ff42013-07-16 20:12:42 -07003631// This should only be called from the main thread. Otherwise it would need
3632// the lock and should use mCurrentState rather than mDrawingState.
3633void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003634 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003635 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003636 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003637
3638 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3639}
3640
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003641void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003642{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003643 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003644 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3645
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003646 if (isLayerTripleBufferingDisabled())
3647 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003648
3649 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003650 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003651 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003652 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003653 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3654 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003655 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003656}
3657
Dan Stozab90cf072015-03-05 11:05:59 -08003658void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3659{
3660 result.appendFormat("Static screen stats:\n");
3661 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3662 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3663 float percent = 100.0f *
3664 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3665 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3666 b + 1, bucketTimeSec, percent);
3667 }
3668 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3669 float percent = 100.0f *
3670 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3671 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3672 NUM_BUCKETS - 1, bucketTimeSec, percent);
3673}
3674
Dan Stozae77c7662016-05-13 11:37:28 -07003675void SurfaceFlinger::recordBufferingStats(const char* layerName,
3676 std::vector<OccupancyTracker::Segment>&& history) {
3677 Mutex::Autolock lock(mBufferingStatsMutex);
3678 auto& stats = mBufferingStats[layerName];
3679 for (const auto& segment : history) {
3680 if (!segment.usedThirdBuffer) {
3681 stats.twoBufferTime += segment.totalTime;
3682 }
3683 if (segment.occupancyAverage < 1.0f) {
3684 stats.doubleBufferedTime += segment.totalTime;
3685 } else if (segment.occupancyAverage < 2.0f) {
3686 stats.tripleBufferedTime += segment.totalTime;
3687 }
3688 ++stats.numSegments;
3689 stats.totalTime += segment.totalTime;
3690 }
3691}
3692
Brian Andersond6927fb2016-07-23 23:37:30 -07003693void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3694 result.appendFormat("Layer frame timestamps:\n");
3695
3696 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3697 const size_t count = currentLayers.size();
3698 for (size_t i=0 ; i<count ; i++) {
3699 currentLayers[i]->dumpFrameEvents(result);
3700 }
3701}
3702
Dan Stozae77c7662016-05-13 11:37:28 -07003703void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3704 result.append("Buffering stats:\n");
3705 result.append(" [Layer name] <Active time> <Two buffer> "
3706 "<Double buffered> <Triple buffered>\n");
3707 Mutex::Autolock lock(mBufferingStatsMutex);
3708 typedef std::tuple<std::string, float, float, float> BufferTuple;
3709 std::map<float, BufferTuple, std::greater<float>> sorted;
3710 for (const auto& statsPair : mBufferingStats) {
3711 const char* name = statsPair.first.c_str();
3712 const BufferingStats& stats = statsPair.second;
3713 if (stats.numSegments == 0) {
3714 continue;
3715 }
3716 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3717 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3718 stats.totalTime;
3719 float doubleBufferRatio = static_cast<float>(
3720 stats.doubleBufferedTime) / stats.totalTime;
3721 float tripleBufferRatio = static_cast<float>(
3722 stats.tripleBufferedTime) / stats.totalTime;
3723 sorted.insert({activeTime, {name, twoBufferRatio,
3724 doubleBufferRatio, tripleBufferRatio}});
3725 }
3726 for (const auto& sortedPair : sorted) {
3727 float activeTime = sortedPair.first;
3728 const BufferTuple& values = sortedPair.second;
3729 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3730 std::get<0>(values).c_str(), activeTime,
3731 std::get<1>(values), std::get<2>(values),
3732 std::get<3>(values));
3733 }
3734 result.append("\n");
3735}
3736
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003737void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3738 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003739 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003740
3741 // TODO: print out if wide-color mode is active or not
3742
3743 for (size_t d = 0; d < mDisplays.size(); d++) {
3744 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3745 int32_t hwcId = displayDevice->getHwcDisplayId();
3746 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3747 continue;
3748 }
3749
3750 result.appendFormat("Display %d color modes:\n", hwcId);
3751 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3752 for (auto&& mode : modes) {
3753 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3754 }
3755
3756 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3757 result.appendFormat(" Current color mode: %s (%d)\n",
3758 decodeColorMode(currentMode).c_str(), currentMode);
3759 }
3760 result.append("\n");
3761}
3762
chaviw1d044282017-09-27 12:19:28 -07003763LayersProto SurfaceFlinger::dumpProtoInfo() const {
3764 LayersProto layersProto;
3765 mCurrentState.traverseInZOrder([&](Layer* layer) {
3766 LayerProto* layerProto = layersProto.add_layers();
3767 layer->writeToProto(layerProto, LayerVector::StateSet::Current);
3768 });
3769
3770 return layersProto;
3771}
3772
Mathias Agopian74d211a2013-04-22 16:55:35 +02003773void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3774 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003775{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003776 bool colorize = false;
3777 if (index < args.size()
3778 && (args[index] == String16("--color"))) {
3779 colorize = true;
3780 index++;
3781 }
3782
3783 Colorizer colorizer(colorize);
3784
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003785 // figure out if we're stuck somewhere
3786 const nsecs_t now = systemTime();
3787 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3788 const nsecs_t inTransaction(mDebugInTransaction);
3789 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3790 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3791
3792 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003793 * Dump library configuration.
3794 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003795
3796 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003797 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003798 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003799 appendSfConfigString(result);
3800 appendUiConfigString(result);
3801 appendGuiConfigString(result);
3802 result.append("\n");
3803
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003804 result.append("\nWide-Color information:\n");
3805 dumpWideColorInfo(result);
3806
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003807 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003808 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003809 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003810 result.append(SyncFeatures::getInstance().toString());
3811 result.append("\n");
3812
Dan Stoza9e56aa02015-11-02 13:00:03 -08003813 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3814
Andy McFadden41d67d72014-04-25 16:58:34 -07003815 colorizer.bold(result);
3816 result.append("DispSync configuration: ");
3817 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003818 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003819 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003820 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003821 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003822 result.append("\n");
3823
Dan Stozab90cf072015-03-05 11:05:59 -08003824 // Dump static screen stats
3825 result.append("\n");
3826 dumpStaticScreenStats(result);
3827 result.append("\n");
3828
Dan Stozae77c7662016-05-13 11:37:28 -07003829 dumpBufferingStats(result);
3830
Andy McFadden4803b742012-09-24 19:07:20 -07003831 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003832 * Dump the visible layer list
3833 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003834 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003835 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003836 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003837
3838 LayersProto layersProto = dumpProtoInfo();
3839 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3840 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003841
3842 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003843 * Dump Display state
3844 */
3845
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003846 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003847 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003848 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003849 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3850 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003851 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003852 }
3853
3854 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003855 * Dump SurfaceFlinger global state
3856 */
3857
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003858 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003859 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003860 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003861
Mathias Agopian888c8222012-08-04 21:10:38 -07003862 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003863 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003864
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003865 colorizer.bold(result);
3866 result.appendFormat("EGL implementation : %s\n",
3867 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3868 colorizer.reset(result);
3869 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003870 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003871
Mathias Agopian875d8e12013-06-07 15:35:48 -07003872 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003873
Mathias Agopian42977342012-08-05 00:40:46 -07003874 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003875 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3876 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003877 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003878 " last eglSwapBuffers() time: %f us\n"
3879 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003880 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003881 " refresh-rate : %f fps\n"
3882 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003883 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003884 " gpu_to_cpu_unsupported : %d\n"
3885 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003886 mLastSwapBufferTime/1000.0,
3887 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003888 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003889 1e9 / activeConfig->getVsyncPeriod(),
3890 activeConfig->getDpiX(),
3891 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003892 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003893
Mathias Agopian74d211a2013-04-22 16:55:35 +02003894 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003895 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003896
Mathias Agopian74d211a2013-04-22 16:55:35 +02003897 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003898 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003899
3900 /*
3901 * VSYNC state
3902 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003903 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003904 result.append("\n");
3905
3906 /*
3907 * HWC layer minidump
3908 */
3909 for (size_t d = 0; d < mDisplays.size(); d++) {
3910 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3911 int32_t hwcId = displayDevice->getHwcDisplayId();
3912 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3913 continue;
3914 }
3915
3916 result.appendFormat("Display %d HWC layers:\n", hwcId);
3917 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003918 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003919 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003920 });
Dan Stozae22aec72016-08-01 13:20:59 -07003921 result.append("\n");
3922 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003923
3924 /*
3925 * Dump HWComposer state
3926 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003927 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003928 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003929 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003930 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003931 result.appendFormat(" h/w composer %s\n",
3932 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003933 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003934
3935 /*
3936 * Dump gralloc state
3937 */
3938 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3939 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003940
3941 /*
3942 * Dump VrFlinger state if in use.
3943 */
3944 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3945 result.append("VrFlinger state:\n");
3946 result.append(mVrFlinger->Dump().c_str());
3947 result.append("\n");
3948 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003949}
3950
Mathias Agopian13127d82013-03-05 17:47:11 -08003951const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003952SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003953 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003954 wp<IBinder> dpy;
3955 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3956 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3957 dpy = mDisplays.keyAt(i);
3958 break;
3959 }
3960 }
3961 if (dpy == NULL) {
3962 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3963 // Just use the primary display so we have something to return
3964 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3965 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003966 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003967}
3968
Keun young Park63f165f2012-08-31 10:53:36 -07003969bool SurfaceFlinger::startDdmConnection()
3970{
3971 void* libddmconnection_dso =
3972 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3973 if (!libddmconnection_dso) {
3974 return false;
3975 }
3976 void (*DdmConnection_start)(const char* name);
3977 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003978 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003979 if (!DdmConnection_start) {
3980 dlclose(libddmconnection_dso);
3981 return false;
3982 }
3983 (*DdmConnection_start)(getServiceName());
3984 return true;
3985}
3986
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003987status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003988 switch (code) {
3989 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003990 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003991 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003992 case CLEAR_ANIMATION_FRAME_STATS:
3993 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003994 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003995 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07003996 case ENABLE_VSYNC_INJECTIONS:
3997 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003998 {
3999 // codes that require permission check
4000 IPCThreadState* ipc = IPCThreadState::self();
4001 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004002 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004003 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004004 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004005 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004006 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004007 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004008 break;
4009 }
Robert Carr1db73f62016-12-21 12:58:51 -08004010 /*
4011 * Calling setTransactionState is safe, because you need to have been
4012 * granted a reference to Client* and Handle* to do anything with it.
4013 *
4014 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4015 */
4016 case SET_TRANSACTION_STATE:
4017 case CREATE_SCOPED_CONNECTION:
4018 {
4019 return OK;
4020 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004021 case CAPTURE_SCREEN:
4022 {
4023 // codes that require permission check
4024 IPCThreadState* ipc = IPCThreadState::self();
4025 const int pid = ipc->getCallingPid();
4026 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004027 if ((uid != AID_GRAPHICS) &&
4028 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004029 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004030 return PERMISSION_DENIED;
4031 }
4032 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004033 }
chaviwa76b2712017-09-20 12:02:26 -07004034 case CAPTURE_LAYERS: {
4035 IPCThreadState* ipc = IPCThreadState::self();
4036 const int pid = ipc->getCallingPid();
4037 const int uid = ipc->getCallingUid();
4038 if ((uid != AID_GRAPHICS) &&
4039 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4040 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4041 return PERMISSION_DENIED;
4042 }
4043 break;
4044 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004045 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004046 return OK;
4047}
4048
4049status_t SurfaceFlinger::onTransact(
4050 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4051{
4052 status_t credentialCheck = CheckTransactCodeCredentials(code);
4053 if (credentialCheck != OK) {
4054 return credentialCheck;
4055 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004056
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004057 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4058 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004059 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004060 IPCThreadState* ipc = IPCThreadState::self();
4061 const int uid = ipc->getCallingUid();
4062 if (CC_UNLIKELY(uid != AID_SYSTEM
4063 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004064 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004065 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004066 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004067 return PERMISSION_DENIED;
4068 }
4069 int n;
4070 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004071 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004072 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004073 return NO_ERROR;
4074 case 1002: // SHOW_UPDATES
4075 n = data.readInt32();
4076 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004077 invalidateHwcGeometry();
4078 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004079 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004080 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004081 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004082 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004083 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004084 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004085 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004086 setTransactionFlags(
4087 eTransactionNeeded|
4088 eDisplayTransactionNeeded|
4089 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004090 return NO_ERROR;
4091 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004092 case 1006:{ // send empty update
4093 signalRefresh();
4094 return NO_ERROR;
4095 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004096 case 1008: // toggle use of hw composer
4097 n = data.readInt32();
4098 mDebugDisableHWC = n ? 1 : 0;
4099 invalidateHwcGeometry();
4100 repaintEverything();
4101 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004102 case 1009: // toggle use of transform hint
4103 n = data.readInt32();
4104 mDebugDisableTransformHint = n ? 1 : 0;
4105 invalidateHwcGeometry();
4106 repaintEverything();
4107 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004108 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004109 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004110 reply->writeInt32(0);
4111 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004112 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004113 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004114 return NO_ERROR;
4115 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004116 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004117 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004118 return NO_ERROR;
4119 }
4120 case 1014: {
4121 // daltonize
4122 n = data.readInt32();
4123 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004124 case 1:
4125 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4126 break;
4127 case 2:
4128 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4129 break;
4130 case 3:
4131 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4132 break;
4133 default:
4134 mDaltonizer.setType(ColorBlindnessType::None);
4135 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004136 }
4137 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004138 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004139 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004140 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004141 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004142 invalidateHwcGeometry();
4143 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004144 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004145 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004146 case 1015: {
4147 // apply a color matrix
4148 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004149 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004150 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004151 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004152 for (size_t j = 0; j < 4; j++) {
4153 mColorMatrix[i][j] = data.readFloat();
4154 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004155 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004156 } else {
4157 mColorMatrix = mat4();
4158 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004159
4160 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4161 // the division by w in the fragment shader
4162 float4 lastRow(transpose(mColorMatrix)[3]);
4163 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4164 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4165 }
4166
Alan Viverette9c5a3332013-09-12 20:04:35 -07004167 invalidateHwcGeometry();
4168 repaintEverything();
4169 return NO_ERROR;
4170 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004171 // This is an experimental interface
4172 // Needs to be shifted to proper binder interface when we productize
4173 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004174 n = data.readInt32();
4175 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004176 return NO_ERROR;
4177 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004178 case 1017: {
4179 n = data.readInt32();
4180 mForceFullDamage = static_cast<bool>(n);
4181 return NO_ERROR;
4182 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004183 case 1018: { // Modify Choreographer's phase offset
4184 n = data.readInt32();
4185 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4186 return NO_ERROR;
4187 }
4188 case 1019: { // Modify SurfaceFlinger's phase offset
4189 n = data.readInt32();
4190 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4191 return NO_ERROR;
4192 }
Irvel468051e2016-06-13 16:44:44 -07004193 case 1020: { // Layer updates interceptor
4194 n = data.readInt32();
4195 if (n) {
4196 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004197 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004198 }
4199 else{
4200 ALOGV("Interceptor disabled");
4201 mInterceptor.disable();
4202 }
4203 return NO_ERROR;
4204 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004205 case 1021: { // Disable HWC virtual displays
4206 n = data.readInt32();
4207 mUseHwcVirtualDisplays = !n;
4208 return NO_ERROR;
4209 }
Romain Guy0147a172017-06-01 13:53:56 -07004210 case 1022: { // Set saturation boost
4211 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4212
4213 invalidateHwcGeometry();
4214 repaintEverything();
4215 return NO_ERROR;
4216 }
Romain Guy54f154a2017-10-24 21:40:32 +01004217 case 1023: { // Set native mode
4218 mForceNativeColorMode = data.readInt32() == 1;
4219
4220 invalidateHwcGeometry();
4221 repaintEverything();
4222 return NO_ERROR;
4223 }
4224 case 1024: { // Is wide color gamut rendering/color management supported?
4225 reply->writeBool(hasWideColorDisplay);
4226 return NO_ERROR;
4227 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004228 }
4229 }
4230 return err;
4231}
4232
Steven Thomas6d8110b2017-08-31 18:24:21 -07004233void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004234 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004235 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004236}
4237
Steven Thomas6d8110b2017-08-31 18:24:21 -07004238void SurfaceFlinger::repaintEverything() {
4239 ConditionalLock _l(mStateLock,
4240 std::this_thread::get_id() != mMainThreadId);
4241 repaintEverythingLocked();
4242}
4243
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004244// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4245class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004246public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004247 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4248 ~WindowDisconnector() {
4249 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004250 }
4251
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004252private:
4253 ANativeWindow* mWindow;
4254 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004255};
4256
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004257static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4258 uint32_t requestedHeight, bool hasWideColorDisplay,
4259 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4260 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4261 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4262
4263 int err = 0;
4264 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4265 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4266 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4267 err |= native_window_set_usage(window, usage);
4268
4269 if (hasWideColorDisplay) {
4270 err |= native_window_set_buffers_data_space(window,
4271 renderEngineUsesWideColor
4272 ? HAL_DATASPACE_DISPLAY_P3
4273 : HAL_DATASPACE_V0_SRGB);
4274 }
4275
4276 if (err != NO_ERROR) {
4277 return BAD_VALUE;
4278 }
4279
4280 /* TODO: Once we have the sync framework everywhere this can use
4281 * server-side waits on the fence that dequeueBuffer returns.
4282 */
4283 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4284 if (err != NO_ERROR) {
4285 return err;
4286 }
4287
4288 return NO_ERROR;
4289}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004290
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004291status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
chaviwa76b2712017-09-20 12:02:26 -07004292 const sp<IGraphicBufferProducer>& producer, Rect sourceCrop,
4293 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4294 int32_t maxLayerZ, bool useIdentityTransform,
4295 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004296 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004297
chaviwa76b2712017-09-20 12:02:26 -07004298 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4299
4300 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4301 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4302
4303 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4304 device, minLayerZ, maxLayerZ, std::placeholders::_1);
4305 return captureScreenCommon(renderArea, traverseLayers, producer, useIdentityTransform);
4306}
4307
4308status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
4309 const sp<IGraphicBufferProducer>& producer,
4310 ISurfaceComposer::Rotation rotation) {
4311 ATRACE_CALL();
4312
4313 class LayerRenderArea : public RenderArea {
4314 public:
4315 LayerRenderArea(const sp<Layer>& layer, ISurfaceComposer::Rotation rotation)
4316 : RenderArea(layer->getCurrentState().active.h, layer->getCurrentState().active.w,
4317 rotation),
4318 mLayer(layer) {}
4319 const Transform& getTransform() const override {
4320 // Make the top level transform the inverse the transform and it's parent so it sets
4321 // the whole capture back to 0,0
4322 return *new Transform(mLayer->getTransform().inverse());
4323 }
4324 Rect getBounds() const override {
4325 const Layer::State& layerState(mLayer->getDrawingState());
4326 return Rect(layerState.active.w, layerState.active.h);
4327 }
4328 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4329 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4330 bool isSecure() const override { return false; }
4331 bool needsFiltering() const override { return false; }
4332
4333 Rect getSourceCrop() const override { return getBounds(); }
4334 bool getWideColorSupport() const override { return false; }
4335 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4336
4337 private:
4338 const sp<Layer>& mLayer;
4339 };
4340
4341 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4342 auto parent = layerHandle->owner.promote();
4343
4344 LayerRenderArea renderArea(parent, rotation);
4345 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4346 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4347 if (!layer->isVisible()) {
4348 return;
4349 }
4350 visitor(layer);
4351 });
4352 };
4353 return captureScreenCommon(renderArea, traverseLayers, producer, false);
4354}
4355
4356status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4357 TraverseLayersFunction traverseLayers,
4358 const sp<IGraphicBufferProducer>& producer,
4359 bool useIdentityTransform) {
4360 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004361
4362 if (CC_UNLIKELY(producer == 0))
4363 return BAD_VALUE;
4364
chaviwa76b2712017-09-20 12:02:26 -07004365 renderArea.updateDimensions();
4366
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004367 // if we have secure windows on this display, never allow the screen capture
4368 // unless the producer interface is local (i.e.: we can take a screenshot for
4369 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004370 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004371
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004372 // create a surface (because we're a producer, and we need to
4373 // dequeue/queue a buffer)
4374 sp<Surface> surface = new Surface(producer, false);
4375
4376 // Put the screenshot Surface into async mode so that
4377 // Layer::headFenceHasSignaled will always return true and we'll latch the
4378 // first buffer regardless of whether or not its acquire fence has
4379 // signaled. This is needed to avoid a race condition in the rotation
4380 // animation. See b/30209608
4381 surface->setAsyncMode(true);
4382
4383 ANativeWindow* window = surface.get();
4384
4385 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4386 if (result != NO_ERROR) {
4387 return result;
4388 }
4389 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4390
4391 ANativeWindowBuffer* buffer = nullptr;
chaviwa76b2712017-09-20 12:02:26 -07004392 result = getWindowBuffer(window, renderArea.getReqWidth(), renderArea.getReqHeight(),
4393 hasWideColorDisplay && !mForceNativeColorMode,
4394 getRenderEngine().usesWideColor(), &buffer);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004395 if (result != NO_ERROR) {
4396 return result;
4397 }
4398
4399 // This mutex protects syncFd and captureResult for communication of the return values from the
4400 // main thread back to this Binder thread
4401 std::mutex captureMutex;
4402 std::condition_variable captureCondition;
4403 std::unique_lock<std::mutex> captureLock(captureMutex);
4404 int syncFd = -1;
4405 std::optional<status_t> captureResult;
4406
4407 sp<LambdaMessage> message = new LambdaMessage([&]() {
4408 // If there is a refresh pending, bug out early and tell the binder thread to try again
4409 // after the refresh.
4410 if (mRefreshPending) {
4411 ATRACE_NAME("Skipping screenshot for now");
4412 std::unique_lock<std::mutex> captureLock(captureMutex);
4413 captureResult = std::make_optional<status_t>(EAGAIN);
4414 captureCondition.notify_one();
4415 return;
4416 }
4417
4418 status_t result = NO_ERROR;
4419 int fd = -1;
4420 {
4421 Mutex::Autolock _l(mStateLock);
chaviwa76b2712017-09-20 12:02:26 -07004422 result = captureScreenImplLocked(renderArea, traverseLayers, buffer,
4423 useIdentityTransform, isLocalScreenshot, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004424 }
4425
4426 {
4427 std::unique_lock<std::mutex> captureLock(captureMutex);
4428 syncFd = fd;
4429 captureResult = std::make_optional<status_t>(result);
4430 captureCondition.notify_one();
4431 }
4432 });
4433
4434 result = postMessageAsync(message);
4435 if (result == NO_ERROR) {
4436 captureCondition.wait(captureLock, [&]() { return captureResult; });
4437 while (*captureResult == EAGAIN) {
4438 captureResult.reset();
4439 result = postMessageAsync(message);
4440 if (result != NO_ERROR) {
4441 return result;
4442 }
4443 captureCondition.wait(captureLock, [&]() { return captureResult; });
4444 }
4445 result = *captureResult;
4446 }
4447
4448 if (result == NO_ERROR) {
4449 // queueBuffer takes ownership of syncFd
4450 result = window->queueBuffer(window, buffer, syncFd);
4451 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004452 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004453}
4454
chaviwa76b2712017-09-20 12:02:26 -07004455void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4456 TraverseLayersFunction traverseLayers, bool yswap,
4457 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004458 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004459
Mathias Agopian3f844832013-08-07 21:24:32 -07004460 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004461
4462 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004463 const auto raWidth = renderArea.getWidth();
4464 const auto raHeight = renderArea.getHeight();
4465
4466 const auto reqWidth = renderArea.getReqWidth();
4467 const auto reqHeight = renderArea.getReqHeight();
4468 Rect sourceCrop = renderArea.getSourceCrop();
4469
4470 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4471 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004472
Dan Stozac1879002014-05-22 15:59:05 -07004473 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004474 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004475 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004476 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004477 }
4478
4479 // ensure that sourceCrop is inside screen
4480 if (sourceCrop.left < 0) {
4481 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4482 }
chaviwa76b2712017-09-20 12:02:26 -07004483 if (sourceCrop.right > raWidth) {
4484 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004485 }
4486 if (sourceCrop.top < 0) {
4487 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4488 }
chaviwa76b2712017-09-20 12:02:26 -07004489 if (sourceCrop.bottom > raHeight) {
4490 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004491 }
4492
chaviwa76b2712017-09-20 12:02:26 -07004493 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
4494 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004495
Mathias Agopian180f10d2013-04-10 22:55:41 -07004496 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004497 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004498
4499 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004500 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4501 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004502 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004503
4504 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004505 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004506
chaviwa76b2712017-09-20 12:02:26 -07004507 traverseLayers([&](Layer* layer) {
4508 if (filtering) layer->setFiltering(true);
4509 layer->draw(renderArea, useIdentityTransform);
4510 if (filtering) layer->setFiltering(false);
4511 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004512}
4513
Dan Stozaabcda352017-06-01 14:37:39 -07004514// A simple RAII class that holds an EGLImage and destroys it either:
4515// a) When the destroy() method is called
4516// b) When the object goes out of scope
4517class ImageHolder {
4518public:
4519 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4520 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004521
Dan Stozaabcda352017-06-01 14:37:39 -07004522 void destroy() {
4523 if (mImage != EGL_NO_IMAGE_KHR) {
4524 eglDestroyImageKHR(mDisplay, mImage);
4525 mImage = EGL_NO_IMAGE_KHR;
4526 }
4527 }
4528
4529private:
4530 const EGLDisplay mDisplay;
4531 EGLImageKHR mImage;
4532};
4533
chaviwa76b2712017-09-20 12:02:26 -07004534status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4535 TraverseLayersFunction traverseLayers,
4536 ANativeWindowBuffer* buffer,
4537 bool useIdentityTransform, bool isLocalScreenshot,
4538 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004539 ATRACE_CALL();
4540
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004541 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004542
4543 traverseLayers([&](Layer* layer) {
4544 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4545 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004546
4547 if (!isLocalScreenshot && secureLayerIsVisible) {
4548 ALOGW("FB is protected: PERMISSION_DENIED");
4549 return PERMISSION_DENIED;
4550 }
4551
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004552 int syncFd = -1;
4553 // create an EGLImage from the buffer so we can later
4554 // turn it into a texture
4555 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4556 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4557 if (image == EGL_NO_IMAGE_KHR) {
4558 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004559 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004560
Dan Stozaabcda352017-06-01 14:37:39 -07004561 // This will automatically destroy the image if we return before calling its destroy method
4562 ImageHolder imageHolder(mEGLDisplay, image);
4563
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004564 // this binds the given EGLImage as a framebuffer for the
4565 // duration of this scope.
4566 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004567 if (imageBond.getStatus() != NO_ERROR) {
4568 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004569 return INVALID_OPERATION;
4570 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004571
Dan Stozaabcda352017-06-01 14:37:39 -07004572 // this will in fact render into our dequeued buffer
4573 // via an FBO, which means we didn't have to create
4574 // an EGLSurface and therefore we're not
4575 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004576 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004577
Dan Stozaabcda352017-06-01 14:37:39 -07004578 // Attempt to create a sync khr object that can produce a sync point. If that
4579 // isn't available, create a non-dupable sync object in the fallback path and
4580 // wait on it directly.
4581 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4582 if (!DEBUG_SCREENSHOTS) {
4583 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4584 // native fence fd will not be populated until flush() is done.
4585 getRenderEngine().flush();
4586 }
4587
4588 if (sync != EGL_NO_SYNC_KHR) {
4589 // get the sync fd
4590 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4591 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4592 ALOGW("captureScreen: failed to dup sync khr object");
4593 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004594 }
Dan Stozaabcda352017-06-01 14:37:39 -07004595 eglDestroySyncKHR(mEGLDisplay, sync);
4596 } else {
4597 // fallback path
4598 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004599 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004600 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4601 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4602 EGLint eglErr = eglGetError();
4603 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4604 ALOGW("captureScreen: fence wait timed out");
4605 } else {
4606 ALOGW_IF(eglErr != EGL_SUCCESS,
4607 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004608 }
4609 eglDestroySyncKHR(mEGLDisplay, sync);
4610 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004611 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004612 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004613 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004614 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004615
4616 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004617 const auto reqWidth = renderArea.getReqWidth();
4618 const auto reqHeight = renderArea.getReqHeight();
4619
Dan Stozaabcda352017-06-01 14:37:39 -07004620 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4621 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004622 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004623 delete [] pixels;
4624 }
4625
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004626 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004627 imageHolder.destroy();
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,
chaviwa76b2712017-09-20 12:02:26 -07004632 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004633 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -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 }
chaviwa76b2712017-09-20 12:02:26 -07004640 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004641
Robert Carr2047fae2016-11-28 14:09:09 -08004642 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004643 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004644 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004645 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4646 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4647 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4648 static_cast<float>(state.color.a));
4649 i++;
4650 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004651 }
4652}
4653
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004654// ---------------------------------------------------------------------------
4655
Dan Stoza412903f2017-04-27 13:42:17 -07004656void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4657 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004658}
4659
Dan Stoza412903f2017-04-27 13:42:17 -07004660void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4661 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004662}
4663
chaviwa76b2712017-09-20 12:02:26 -07004664void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4665 int32_t maxLayerZ,
4666 const LayerVector::Visitor& visitor) {
4667 // We loop through the first level of layers without traversing,
4668 // as we need to interpret min/max layer Z in the top level Z space.
4669 for (const auto& layer : mDrawingState.layersSortedByZ) {
4670 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4671 continue;
4672 }
4673 const Layer::State& state(layer->getDrawingState());
4674 if (state.z < minLayerZ || state.z > maxLayerZ) {
4675 continue;
4676 }
4677 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4678 if (!layer->isVisible()) {
4679 return;
4680 }
4681 visitor(layer);
4682 });
4683 }
4684}
4685
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004686}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004687
4688
4689#if defined(__gl_h_)
4690#error "don't include gl/gl.h in this file"
4691#endif
4692
4693#if defined(__gl2_h_)
4694#error "don't include gl2/gl2.h in this file"
4695#endif