blob: 5be1e284373e633a39423b3607325deea9105204 [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();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001523 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001524 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001525 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001526
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001527 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001528
1529 mHadClientComposition = false;
1530 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1531 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1532 mHadClientComposition = mHadClientComposition ||
1533 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1534 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001535
Dan Stoza9e56aa02015-11-02 13:00:03 -08001536 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001537}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001538
Mathias Agopiancd60f992012-08-16 16:28:27 -07001539void SurfaceFlinger::doDebugFlashRegions()
1540{
1541 // is debugging enabled
1542 if (CC_LIKELY(!mDebugRegion))
1543 return;
1544
1545 const bool repaintEverything = mRepaintEverything;
1546 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1547 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001548 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001549 // transform the dirty region into this screen's coordinate space
1550 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1551 if (!dirtyRegion.isEmpty()) {
1552 // redraw the whole screen
1553 doComposeSurfaces(hw, Region(hw->bounds()));
1554
1555 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001556 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001557 RenderEngine& engine(getRenderEngine());
1558 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1559
Mathias Agopianda27af92012-09-13 18:17:13 -07001560 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001561 }
1562 }
1563 }
1564
1565 postFramebuffer();
1566
1567 if (mDebugRegion > 1) {
1568 usleep(mDebugRegion * 1000);
1569 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001570
Dan Stoza9e56aa02015-11-02 13:00:03 -08001571 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001572 auto& displayDevice = mDisplays[displayId];
1573 if (!displayDevice->isDisplayOn()) {
1574 continue;
1575 }
1576
1577 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001578 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1579 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001580 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581}
1582
Adrian Roos1e1a1282017-11-01 19:05:31 +01001583void SurfaceFlinger::doTracing(const char* where) {
1584 ATRACE_CALL();
1585 ATRACE_NAME(where);
1586 if (CC_UNLIKELY(mTracing.isEnabled())) {
1587 mTracing.traceLayers(where, dumpProtoInfo());
1588 }
1589}
1590
Brian Andersond6927fb2016-07-23 23:37:30 -07001591void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001593 ATRACE_CALL();
1594 ALOGV("preComposition");
1595
Mathias Agopiancd60f992012-08-16 16:28:27 -07001596 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001597 mDrawingState.traverseInZOrder([&](Layer* layer) {
1598 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001599 needExtraInvalidate = true;
1600 }
Robert Carr2047fae2016-11-28 14:09:09 -08001601 });
1602
Mathias Agopiancd60f992012-08-16 16:28:27 -07001603 if (needExtraInvalidate) {
1604 signalLayerUpdate();
1605 }
1606}
1607
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001608void SurfaceFlinger::updateCompositorTiming(
1609 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1610 std::shared_ptr<FenceTime>& presentFenceTime) {
1611 // Update queue of past composite+present times and determine the
1612 // most recently known composite to present latency.
1613 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1614 nsecs_t compositeToPresentLatency = -1;
1615 while (!mCompositePresentTimes.empty()) {
1616 CompositePresentTime& cpt = mCompositePresentTimes.front();
1617 // Cached values should have been updated before calling this method,
1618 // which helps avoid duplicate syscalls.
1619 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1620 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1621 break;
1622 }
1623 compositeToPresentLatency = displayTime - cpt.composite;
1624 mCompositePresentTimes.pop();
1625 }
1626
1627 // Don't let mCompositePresentTimes grow unbounded, just in case.
1628 while (mCompositePresentTimes.size() > 16) {
1629 mCompositePresentTimes.pop();
1630 }
1631
Brian Andersond0010582017-03-07 13:20:31 -08001632 setCompositorTimingSnapped(
1633 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1634}
1635
1636void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1637 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001638 // Integer division and modulo round toward 0 not -inf, so we need to
1639 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001640 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001641 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1642 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1643
Brian Andersond0010582017-03-07 13:20:31 -08001644 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1645 if (idealLatency <= 0) {
1646 idealLatency = vsyncInterval;
1647 }
1648
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001649 // Snap the latency to a value that removes scheduling jitter from the
1650 // composition and present times, which often have >1ms of jitter.
1651 // Reducing jitter is important if an app attempts to extrapolate
1652 // something (such as user input) to an accurate diasplay time.
1653 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1654 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001655 nsecs_t bias = vsyncInterval / 2;
1656 int64_t extraVsyncs =
1657 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1658 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1659 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001660
Brian Andersond0010582017-03-07 13:20:31 -08001661 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001662 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1663 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001664 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001665}
1666
1667void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001668{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001669 ATRACE_CALL();
1670 ALOGV("postComposition");
1671
Brian Anderson3546a3f2016-07-14 11:51:14 -07001672 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001673 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001674 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001675 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001676 }
1677
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001678 // |mStateLock| not needed as we are on the main thread
1679 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001680
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001681 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001682 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1683 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1684 glCompositionDoneFenceTime =
1685 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1686 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1687 } else {
1688 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1689 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001690
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001691 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001692 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1693 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1694 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001695
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001696 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1697 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1698
1699 // We use the refreshStartTime which might be sampled a little later than
1700 // when we started doing work for this frame, but that should be okay
1701 // since updateCompositorTiming has snapping logic.
1702 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001703 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001704 CompositorTiming compositorTiming;
1705 {
1706 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1707 compositorTiming = mCompositorTiming;
1708 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001709
Robert Carr2047fae2016-11-28 14:09:09 -08001710 mDrawingState.traverseInZOrder([&](Layer* layer) {
1711 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001712 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001713 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001714 recordBufferingStats(layer->getName().string(),
1715 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001716 }
Robert Carr2047fae2016-11-28 14:09:09 -08001717 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001718
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001719 if (presentFenceTime->isValid()) {
1720 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001721 enableHardwareVsync();
1722 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001723 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001724 }
1725 }
1726
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001727 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001728 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001729 enableHardwareVsync();
1730 }
1731 }
1732
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001733 if (mAnimCompositionPending) {
1734 mAnimCompositionPending = false;
1735
Brian Anderson4e606e32017-03-16 15:34:57 -07001736 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001737 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001738 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001739 } else {
1740 // The HWC doesn't support present fences, so use the refresh
1741 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001742 nsecs_t presentTime =
1743 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001744 mAnimFrameTracker.setActualPresentTime(presentTime);
1745 }
1746 mAnimFrameTracker.advanceFrame();
1747 }
Dan Stozab90cf072015-03-05 11:05:59 -08001748
1749 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1750 return;
1751 }
1752
1753 nsecs_t currentTime = systemTime();
1754 if (mHasPoweredOff) {
1755 mHasPoweredOff = false;
1756 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001757 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001758 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001759 if (numPeriods < NUM_BUCKETS - 1) {
1760 mFrameBuckets[numPeriods] += elapsedTime;
1761 } else {
1762 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1763 }
1764 mTotalTime += elapsedTime;
1765 }
1766 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001767}
1768
1769void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001770 ATRACE_CALL();
1771 ALOGV("rebuildLayerStacks");
1772
Mathias Agopiancd60f992012-08-16 16:28:27 -07001773 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001774 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001775 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001776 mVisibleRegionsDirty = false;
1777 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001778
Jeff Sharkey76488112017-02-27 14:15:18 -07001779 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1780 Region opaqueRegion;
1781 Region dirtyRegion;
1782 Vector<sp<Layer>> layersSortedByZ;
1783 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1784 const Transform& tr(displayDevice->getTransform());
1785 const Rect bounds(displayDevice->getBounds());
1786 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001787 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001788
Jeff Sharkey76488112017-02-27 14:15:18 -07001789 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001790 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1791 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001792 Region drawRegion(tr.transform(
1793 layer->visibleNonTransparentRegion));
1794 drawRegion.andSelf(bounds);
1795 if (!drawRegion.isEmpty()) {
1796 layersSortedByZ.add(layer);
1797 } else {
1798 // Clear out the HWC layer if this layer was
1799 // previously visible, but no longer is
Steven Thomasb02664d2017-07-26 18:48:28 -07001800 layer->destroyHwcLayer(
1801 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001802 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001803 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001804 // WM changes displayDevice->layerStack upon sleep/awake.
1805 // Here we make sure we delete the HWC layers even if
1806 // WM changed their layer stack.
Steven Thomasb02664d2017-07-26 18:48:28 -07001807 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001808 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001809 });
1810 }
1811 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1812 displayDevice->undefinedRegion.set(bounds);
1813 displayDevice->undefinedRegion.subtractSelf(
1814 tr.transform(opaqueRegion));
1815 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001816 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001817 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001818}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001819
Romain Guy0147a172017-06-01 13:53:56 -07001820mat4 SurfaceFlinger::computeSaturationMatrix() const {
1821 if (mSaturation == 1.0f) {
1822 return mat4();
1823 }
1824
1825 // Rec.709 luma coefficients
1826 float3 luminance{0.213f, 0.715f, 0.072f};
1827 luminance *= 1.0f - mSaturation;
1828 return mat4(
1829 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1830 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1831 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1832 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1833 );
1834}
1835
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001836// pickColorMode translates a given dataspace into the best available color mode.
1837// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001838android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001839 if (mForceNativeColorMode) {
1840 return HAL_COLOR_MODE_NATIVE;
1841 }
1842
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001843 switch (dataSpace) {
1844 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1845 // system expects.
1846 case HAL_DATASPACE_UNKNOWN:
1847 case HAL_DATASPACE_SRGB:
1848 case HAL_DATASPACE_V0_SRGB:
1849 return HAL_COLOR_MODE_SRGB;
1850 break;
1851
1852 case HAL_DATASPACE_DISPLAY_P3:
1853 return HAL_COLOR_MODE_DISPLAY_P3;
1854 break;
1855
1856 default:
1857 // TODO (courtneygo): Do we want to assert an error here?
1858 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1859 dataSpace);
1860 return HAL_COLOR_MODE_SRGB;
1861 break;
1862 }
1863}
1864
Romain Guy0147a172017-06-01 13:53:56 -07001865android_dataspace SurfaceFlinger::bestTargetDataSpace(
1866 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001867 // Only support sRGB and Display-P3 right now.
1868 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1869 return HAL_DATASPACE_DISPLAY_P3;
1870 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001871 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1872 return HAL_DATASPACE_DISPLAY_P3;
1873 }
1874 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1875 return HAL_DATASPACE_DISPLAY_P3;
1876 }
1877
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001878 return HAL_DATASPACE_V0_SRGB;
1879}
1880
Mathias Agopiancd60f992012-08-16 16:28:27 -07001881void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001882 ATRACE_CALL();
1883 ALOGV("setUpHWComposer");
1884
Jesse Hall028dc8f2013-08-20 16:35:32 -07001885 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001886 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1887 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1888 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1889
1890 // If nothing has changed (!dirty), don't recompose.
1891 // If something changed, but we don't currently have any visible layers,
1892 // and didn't when we last did a composition, then skip it this time.
1893 // The second rule does two things:
1894 // - When all layers are removed from a display, we'll emit one black
1895 // frame, then nothing more until we get new layers.
1896 // - When a display is created with a private layer stack, we won't
1897 // emit any black frames until a layer is added to the layer stack.
1898 bool mustRecompose = dirty && !(empty && wasEmpty);
1899
1900 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1901 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1902 mustRecompose ? "doing" : "skipping",
1903 dirty ? "+" : "-",
1904 empty ? "+" : "-",
1905 wasEmpty ? "+" : "-");
1906
Dan Stoza71433162014-02-04 16:22:36 -08001907 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001908
1909 if (mustRecompose) {
1910 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1911 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001912 }
1913
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 // build the h/w work list
1915 if (CC_UNLIKELY(mGeometryInvalid)) {
1916 mGeometryInvalid = false;
1917 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1918 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1919 const auto hwcId = displayDevice->getHwcDisplayId();
1920 if (hwcId >= 0) {
1921 const Vector<sp<Layer>>& currentLayers(
1922 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001923 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001924 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001926 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001927 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001928 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001929 }
1930 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001931
Robert Carrae060832016-11-28 10:51:00 -08001932 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001933 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001935 }
1936 }
1937 }
1938 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939 }
Riley Andrews03414a12014-07-01 14:22:59 -07001940
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001941
Romain Guy0147a172017-06-01 13:53:56 -07001942 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001943
Dan Stoza9e56aa02015-11-02 13:00:03 -08001944 // Set the per-frame data
1945 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1946 auto& displayDevice = mDisplays[displayId];
1947 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001948
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 if (hwcId < 0) {
1950 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001951 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001952 if (colorMatrix != mPreviousColorMatrix) {
1953 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1954 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1955 "display %zd: %d", displayId, result);
1956 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1958 layer->setPerFrameData(displayDevice);
1959 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001960
1961 if (hasWideColorDisplay) {
1962 android_color_mode newColorMode;
1963 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1964
1965 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1966 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1967 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1968 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1969 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1970 }
1971 newColorMode = pickColorMode(newDataSpace);
1972
Thierry Strudel2924d012017-08-14 15:19:37 -07001973 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001974 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001975 }
1976
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001977 mPreviousColorMatrix = colorMatrix;
1978
Dan Stoza9e56aa02015-11-02 13:00:03 -08001979 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001980 auto& displayDevice = mDisplays[displayId];
1981 if (!displayDevice->isDisplayOn()) {
1982 continue;
1983 }
1984
1985 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001986 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1987 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001988 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001989}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001990
Mathias Agopiancd60f992012-08-16 16:28:27 -07001991void SurfaceFlinger::doComposition() {
1992 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001993 ALOGV("doComposition");
1994
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001995 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001996 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001997 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001998 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001999 // transform the dirty region into this screen's coordinate space
2000 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002001
2002 // repaint the framebuffer (if needed)
2003 doDisplayComposition(hw, dirtyRegion);
2004
Mathias Agopiancd60f992012-08-16 16:28:27 -07002005 hw->dirtyRegion.clear();
2006 hw->flip(hw->swapRegion);
2007 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07002008 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002009 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002010 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002011}
2012
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002013void SurfaceFlinger::postFramebuffer()
2014{
Mathias Agopian841cde52012-03-01 15:44:37 -08002015 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002016 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002017
Mathias Agopiana44b0412011-10-16 18:46:35 -07002018 const nsecs_t now = systemTime();
2019 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002020
Dan Stoza9e56aa02015-11-02 13:00:03 -08002021 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2022 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002023 if (!displayDevice->isDisplayOn()) {
2024 continue;
2025 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002026 const auto hwcId = displayDevice->getHwcDisplayId();
2027 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002028 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002029 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002030 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002031 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002032 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2033 sp<Fence> releaseFence = Fence::NO_FENCE;
2034 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
2035 releaseFence = displayDevice->getClientTargetAcquireFence();
2036 } else {
2037 auto hwcLayer = layer->getHwcLayer(hwcId);
2038 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002039 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 layer->onLayerDisplayed(releaseFence);
2041 }
2042 if (hwcId >= 0) {
2043 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002044 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002045 }
2046
Mathias Agopiana44b0412011-10-16 18:46:35 -07002047 mLastSwapBufferTime = systemTime() - now;
2048 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002049
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002050 // |mStateLock| not needed as we are on the main thread
2051 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002052 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2053 logFrameStats();
2054 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002055}
2056
Mathias Agopian87baae12012-07-31 12:38:26 -07002057void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002058{
Mathias Agopian841cde52012-03-01 15:44:37 -08002059 ATRACE_CALL();
2060
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002061 // here we keep a copy of the drawing state (that is the state that's
2062 // going to be overwritten by handleTransactionLocked()) outside of
2063 // mStateLock so that the side-effects of the State assignment
2064 // don't happen with mStateLock held (which can cause deadlocks).
2065 State drawingState(mDrawingState);
2066
Mathias Agopianca4d3602011-05-19 15:38:14 -07002067 Mutex::Autolock _l(mStateLock);
2068 const nsecs_t now = systemTime();
2069 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002070
Mathias Agopianca4d3602011-05-19 15:38:14 -07002071 // Here we're guaranteed that some transaction flags are set
2072 // so we can call handleTransactionLocked() unconditionally.
2073 // We call getTransactionFlags(), which will also clear the flags,
2074 // with mStateLock held to guarantee that mCurrentState won't change
2075 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002076
Mathias Agopiane57f2922012-08-09 16:29:12 -07002077 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002078 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002079
Mathias Agopianca4d3602011-05-19 15:38:14 -07002080 mLastTransactionTime = systemTime() - now;
2081 mDebugInTransaction = 0;
2082 invalidateHwcGeometry();
2083 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002084}
2085
Mathias Agopian87baae12012-07-31 12:38:26 -07002086void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002087{
Dan Stoza7dde5992015-05-22 09:51:44 -07002088 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002089 mCurrentState.traverseInZOrder([](Layer* layer) {
2090 layer->notifyAvailableFrames();
2091 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002092
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093 /*
2094 * Traversal of the children
2095 * (perform the transaction for each of them if needed)
2096 */
2097
Mathias Agopian3559b072012-08-15 13:46:03 -07002098 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002099 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002100 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002101 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002102
2103 const uint32_t flags = layer->doTransaction(0);
2104 if (flags & Layer::eVisibleRegion)
2105 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002106 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002107 }
2108
2109 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002110 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002111 */
2112
Mathias Agopiane57f2922012-08-09 16:29:12 -07002113 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002114 // here we take advantage of Vector's copy-on-write semantics to
2115 // improve performance by skipping the transaction entirely when
2116 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002117 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2118 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002119 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002120 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002121 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002122 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002123
2124 // find the displays that were removed
2125 // (ie: in drawing state but not in current state)
2126 // also handle displays that changed
2127 // (ie: displays that are in both lists)
2128 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002129 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2130 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002131 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002132 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002133 // Call makeCurrent() on the primary display so we can
2134 // be sure that nothing associated with this display
2135 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002136 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002137 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002138 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002139 if (hw != NULL)
2140 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002141 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002142 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002143 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002144 } else {
2145 ALOGW("trying to remove the main display");
2146 }
2147 } else {
2148 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002149 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002150 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002151 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2152 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002153 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002154 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002155 // recreating the DisplayDevice, so we just remove it
2156 // from the drawing state, so that it get re-added
2157 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002158 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002159 if (hw != NULL)
2160 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002161 mDisplays.removeItem(display);
2162 mDrawingState.displays.removeItemsAt(i);
2163 dc--; i--;
2164 // at this point we must loop to the next item
2165 continue;
2166 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002167
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002168 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002169 if (disp != NULL) {
2170 if (state.layerStack != draw[i].layerStack) {
2171 disp->setLayerStack(state.layerStack);
2172 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002173 if ((state.orientation != draw[i].orientation)
2174 || (state.viewport != draw[i].viewport)
2175 || (state.frame != draw[i].frame))
2176 {
2177 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002178 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002179 }
Michael Lentine47e45402014-07-18 15:34:25 -07002180 if (state.width != draw[i].width || state.height != draw[i].height) {
2181 disp->setDisplaySize(state.width, state.height);
2182 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002183 }
2184 }
2185 }
2186
2187 // find displays that were added
2188 // (ie: in current state but not in drawing state)
2189 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002190 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002191 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002192
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002193 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002194 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002195 sp<IGraphicBufferProducer> bqProducer;
2196 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002197 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002198
Dan Stoza9e56aa02015-11-02 13:00:03 -08002199 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002200 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002201 // Virtual displays without a surface are dormant:
2202 // they have external state (layer stack, projection,
2203 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002204 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002205
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002206 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002207 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002208 int width = 0;
2209 int status = state.surface->query(
2210 NATIVE_WINDOW_WIDTH, &width);
2211 ALOGE_IF(status != NO_ERROR,
2212 "Unable to query width (%d)", status);
2213 int height = 0;
2214 status = state.surface->query(
2215 NATIVE_WINDOW_HEIGHT, &height);
2216 ALOGE_IF(status != NO_ERROR,
2217 "Unable to query height (%d)", status);
2218 int intFormat = 0;
2219 status = state.surface->query(
2220 NATIVE_WINDOW_FORMAT, &intFormat);
2221 ALOGE_IF(status != NO_ERROR,
2222 "Unable to query format (%d)", status);
2223 auto format = static_cast<android_pixel_format_t>(
2224 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002225
Dan Stoza8cf150a2016-08-02 10:27:31 -07002226 mHwc->allocateVirtualDisplay(width, height, &format,
2227 &hwcId);
2228 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002229
Dan Stoza5cf424b2016-05-20 14:02:39 -07002230 // TODO: Plumb requested format back up to consumer
2231
Dan Stoza9e56aa02015-11-02 13:00:03 -08002232 sp<VirtualDisplaySurface> vds =
2233 new VirtualDisplaySurface(*mHwc,
2234 hwcId, state.surface, bqProducer,
2235 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002236
2237 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002238 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002239 }
2240 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002241 ALOGE_IF(state.surface!=NULL,
2242 "adding a supported display, but rendering "
2243 "surface is provided (%p), ignoring it",
2244 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002245
2246 hwcId = state.type;
2247 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2248 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002249 }
2250
2251 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002252 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002253 sp<DisplayDevice> hw =
2254 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2255 dispSurface, producer,
2256 mRenderEngine->getEGLConfig(),
2257 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002258 hw->setLayerStack(state.layerStack);
2259 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002260 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002261 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002262 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002263 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002264 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002265 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002266 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002267 }
2268 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002269 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002270 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002271
Mathias Agopian84300952012-11-21 16:02:13 -08002272 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2273 // The transform hint might have changed for some layers
2274 // (either because a display has changed, or because a layer
2275 // as changed).
2276 //
2277 // Walk through all the layers in currentLayers,
2278 // and update their transform hint.
2279 //
2280 // If a layer is visible only on a single display, then that
2281 // display is used to calculate the hint, otherwise we use the
2282 // default display.
2283 //
2284 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2285 // the hint is set before we acquire a buffer from the surface texture.
2286 //
2287 // NOTE: layer transactions have taken place already, so we use their
2288 // drawing state. However, SurfaceFlinger's own transaction has not
2289 // happened yet, so we must use the current state layer list
2290 // (soon to become the drawing state list).
2291 //
2292 sp<const DisplayDevice> disp;
2293 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002294 bool first = true;
2295 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002296 // NOTE: we rely on the fact that layers are sorted by
2297 // layerStack first (so we don't have to traverse the list
2298 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002299 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002300 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002301 currentlayerStack = layerStack;
2302 // figure out if this layerstack is mirrored
2303 // (more than one display) if so, pick the default display,
2304 // if not, pick the only display it's on.
2305 disp.clear();
2306 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2307 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002308 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002309 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002310 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002311 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002312 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002313 break;
2314 }
2315 }
2316 }
2317 }
Chet Haase91d25932013-04-11 15:24:55 -07002318 if (disp == NULL) {
2319 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2320 // redraw after transform hint changes. See bug 8508397.
2321
2322 // could be null when this layer is using a layerStack
2323 // that is not visible on any display. Also can occur at
2324 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002325 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002326 }
Chet Haase91d25932013-04-11 15:24:55 -07002327 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002328
2329 first = false;
2330 });
Mathias Agopian84300952012-11-21 16:02:13 -08002331 }
2332
2333
Mathias Agopian3559b072012-08-15 13:46:03 -07002334 /*
2335 * Perform our own transaction if needed
2336 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002337
2338 if (mLayersAdded) {
2339 mLayersAdded = false;
2340 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002341 mVisibleRegionsDirty = true;
2342 }
2343
2344 // some layers might have been removed, so
2345 // we need to update the regions they're exposing.
2346 if (mLayersRemoved) {
2347 mLayersRemoved = false;
2348 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002349 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002350 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002351 // this layer is not visible anymore
2352 // TODO: we could traverse the tree from front to back and
2353 // compute the actual visible region
2354 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002355 Region visibleReg;
2356 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002357 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002358 }
Robert Carr2047fae2016-11-28 14:09:09 -08002359 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002360 }
2361
2362 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002363
2364 updateCursorAsync();
2365}
2366
2367void SurfaceFlinger::updateCursorAsync()
2368{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002369 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2370 auto& displayDevice = mDisplays[displayId];
2371 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002372 continue;
2373 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002374
2375 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2376 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002377 }
2378 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002379}
2380
2381void SurfaceFlinger::commitTransaction()
2382{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002383 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002384 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002385 for (const auto& l : mLayersPendingRemoval) {
2386 recordBufferingStats(l->getName().string(),
2387 l->getOccupancyHistory(true));
2388 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002389 }
2390 mLayersPendingRemoval.clear();
2391 }
2392
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002393 // If this transaction is part of a window animation then the next frame
2394 // we composite should be considered an animation as well.
2395 mAnimCompositionPending = mAnimTransactionPending;
2396
Mathias Agopian4fec8732012-06-29 14:12:52 -07002397 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002398 mDrawingState.traverseInZOrder([](Layer* layer) {
2399 layer->commitChildList();
2400 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002401 mTransactionPending = false;
2402 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002403 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002404}
2405
Chia-I Wuab0c3192017-08-01 11:29:00 -07002406void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002407 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002408{
Mathias Agopian841cde52012-03-01 15:44:37 -08002409 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002410 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002411
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002412 Region aboveOpaqueLayers;
2413 Region aboveCoveredLayers;
2414 Region dirty;
2415
Mathias Agopian87baae12012-07-31 12:38:26 -07002416 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002417
Robert Carr2047fae2016-11-28 14:09:09 -08002418 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002419 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002420 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002421
Jesse Hall01e29052013-02-19 16:13:35 -08002422 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002423 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002424 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002425
Mathias Agopianab028732010-03-16 16:41:46 -07002426 /*
2427 * opaqueRegion: area of a surface that is fully opaque.
2428 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002429 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002430
2431 /*
2432 * visibleRegion: area of a surface that is visible on screen
2433 * and not fully transparent. This is essentially the layer's
2434 * footprint minus the opaque regions above it.
2435 * Areas covered by a translucent surface are considered visible.
2436 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002437 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002438
2439 /*
2440 * coveredRegion: area of a surface that is covered by all
2441 * visible regions above it (which includes the translucent areas).
2442 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002443 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002444
Jesse Halla8026d22012-09-25 13:25:04 -07002445 /*
2446 * transparentRegion: area of a surface that is hinted to be completely
2447 * transparent. This is only used to tell when the layer has no visible
2448 * non-transparent regions and can be removed from the layer list. It
2449 * does not affect the visibleRegion of this layer or any layers
2450 * beneath it. The hint may not be correct if apps don't respect the
2451 * SurfaceView restrictions (which, sadly, some don't).
2452 */
2453 Region transparentRegion;
2454
Mathias Agopianab028732010-03-16 16:41:46 -07002455
2456 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002457 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002458 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002459 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002460 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002461 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002462 if (!visibleRegion.isEmpty()) {
2463 // Remove the transparent area from the visible region
2464 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002465 if (tr.preserveRects()) {
2466 // transform the transparent region
2467 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002468 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002469 // transformation too complex, can't do the
2470 // transparent region optimization.
2471 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002472 }
Mathias Agopianab028732010-03-16 16:41:46 -07002473 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002474
Mathias Agopianab028732010-03-16 16:41:46 -07002475 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002476 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002477 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002478 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2479 // the opaque region is the layer's footprint
2480 opaqueRegion = visibleRegion;
2481 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482 }
2483 }
2484
Mathias Agopianab028732010-03-16 16:41:46 -07002485 // Clip the covered region to the visible region
2486 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2487
2488 // Update aboveCoveredLayers for next (lower) layer
2489 aboveCoveredLayers.orSelf(visibleRegion);
2490
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491 // subtract the opaque region covered by the layers above us
2492 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002493
2494 // compute this layer's dirty region
2495 if (layer->contentDirty) {
2496 // we need to invalidate the whole region
2497 dirty = visibleRegion;
2498 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002499 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500 layer->contentDirty = false;
2501 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002502 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002503 * the exposed region consists of two components:
2504 * 1) what's VISIBLE now and was COVERED before
2505 * 2) what's EXPOSED now less what was EXPOSED before
2506 *
2507 * note that (1) is conservative, we start with the whole
2508 * visible region but only keep what used to be covered by
2509 * something -- which mean it may have been exposed.
2510 *
2511 * (2) handles areas that were not covered by anything but got
2512 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002513 */
Mathias Agopianab028732010-03-16 16:41:46 -07002514 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002515 const Region oldVisibleRegion = layer->visibleRegion;
2516 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002517 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2518 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519 }
2520 dirty.subtractSelf(aboveOpaqueLayers);
2521
2522 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002523 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524
Mathias Agopianab028732010-03-16 16:41:46 -07002525 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002527
Jesse Halla8026d22012-09-25 13:25:04 -07002528 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002529 layer->setVisibleRegion(visibleRegion);
2530 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002531 layer->setVisibleNonTransparentRegion(
2532 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002533 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002534
Mathias Agopian87baae12012-07-31 12:38:26 -07002535 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536}
2537
Chia-I Wuab0c3192017-08-01 11:29:00 -07002538void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002539 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002540 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002541 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002542 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002543 }
2544 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002545}
2546
Dan Stoza6b9454d2014-11-07 16:00:59 -08002547bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002548{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002549 ALOGV("handlePageFlip");
2550
Brian Andersond6927fb2016-07-23 23:37:30 -07002551 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552
Mathias Agopian4fec8732012-06-29 14:12:52 -07002553 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002554 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002555 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002556
2557 // Store the set of layers that need updates. This set must not change as
2558 // buffers are being latched, as this could result in a deadlock.
2559 // Example: Two producers share the same command stream and:
2560 // 1.) Layer 0 is latched
2561 // 2.) Layer 0 gets a new frame
2562 // 2.) Layer 1 gets a new frame
2563 // 3.) Layer 1 is latched.
2564 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2565 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002566 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002567 if (layer->hasQueuedFrame()) {
2568 frameQueued = true;
2569 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002570 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002571 } else {
2572 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002573 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002574 } else {
2575 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002576 }
Robert Carr2047fae2016-11-28 14:09:09 -08002577 });
2578
Dan Stoza9e56aa02015-11-02 13:00:03 -08002579 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002580 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002581 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002582 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002583 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002584 newDataLatched = true;
2585 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002586 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002587
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002588 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002589
2590 // If we will need to wake up at some time in the future to deal with a
2591 // queued frame that shouldn't be displayed during this vsync period, wake
2592 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002593 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002594 signalLayerUpdate();
2595 }
2596
2597 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002598 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599}
2600
Mathias Agopianad456f92011-01-13 17:53:01 -08002601void SurfaceFlinger::invalidateHwcGeometry()
2602{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002603 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002604}
2605
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002606
Fabien Sanglard830b8472016-11-30 16:35:58 -08002607void SurfaceFlinger::doDisplayComposition(
2608 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002609 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610{
Dan Stoza71433162014-02-04 16:22:36 -08002611 // We only need to actually compose the display if:
2612 // 1) It is being handled by hardware composer, which may need this to
2613 // keep its virtual display state machine in sync, or
2614 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002615 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002616 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002617 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002618 return;
2619 }
2620
Dan Stoza9e56aa02015-11-02 13:00:03 -08002621 ALOGV("doDisplayComposition");
2622
Mathias Agopian87baae12012-07-31 12:38:26 -07002623 Region dirtyRegion(inDirtyRegion);
2624
Mathias Agopianb8a55602009-06-26 19:06:36 -07002625 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002626 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002627
Fabien Sanglard830b8472016-11-30 16:35:58 -08002628 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002629 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002630 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2631 // takes a rectangle, we must make sure to update that whole
2632 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002633 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002634 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002635 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002636 // We need to redraw the rectangle that will be updated
2637 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002638 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002639 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002640 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002641 } else {
2642 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002643 dirtyRegion.set(displayDevice->bounds());
2644 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645 }
2646 }
2647
Fabien Sanglard830b8472016-11-30 16:35:58 -08002648 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002649
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002650 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002651 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002652
2653 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002654 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002655}
2656
Dan Stoza9e56aa02015-11-02 13:00:03 -08002657bool SurfaceFlinger::doComposeSurfaces(
2658 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002659{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002660 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002661
chaviwa76b2712017-09-20 12:02:26 -07002662 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002664
2665 mat4 oldColorMatrix;
2666 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2667 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2668 if (applyColorMatrix) {
2669 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2670 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2671 }
2672
Dan Stoza9e56aa02015-11-02 13:00:03 -08002673 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2674 if (hasClientComposition) {
2675 ALOGV("hasClientComposition");
2676
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002677#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01002678 mRenderEngine->setWideColor(
2679 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2680 mRenderEngine->setColorMode(mForceNativeColorMode ?
2681 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002682#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002683 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002684 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002685 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002686 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002687
2688 // |mStateLock| not needed as we are on the main thread
2689 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002690 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2691 }
2692 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002693 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002694
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002695 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002696 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2697 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002698 // when using overlays, we assume a fully transparent framebuffer
2699 // NOTE: we could reduce how much we need to clear, for instance
2700 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002701 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002702 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002703 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002704 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002705 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002706 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002707
2708 // we remove the scissor part
2709 // we're left with the letterbox region
2710 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002711 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002712
2713 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002714 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002715
2716 // but limit it to the dirty region
2717 region.andSelf(dirty);
2718
Mathias Agopianb9494d52012-04-18 02:28:45 -07002719 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002720 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002721 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002722 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002723 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002724 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002725
Dan Stoza9e56aa02015-11-02 13:00:03 -08002726 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002727 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002728 // scissor on the main display. It should never be needed
2729 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002730 const Rect& bounds(displayDevice->getBounds());
2731 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002732 if (scissor != bounds) {
2733 // scissor doesn't match the screen's dimensions, so we
2734 // need to clear everything outside of it and enable
2735 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002736
Mathias Agopianf45c5102012-10-24 16:29:17 -07002737 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002738 const uint32_t height = displayDevice->getHeight();
2739 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002740 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002741 }
2742 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002743 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002744
Mathias Agopian85d751c2012-08-29 16:59:24 -07002745 /*
2746 * and then, render the layers targeted at the framebuffer
2747 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002748
Dan Stoza9e56aa02015-11-02 13:00:03 -08002749 ALOGV("Rendering client layers");
2750 const Transform& displayTransform = displayDevice->getTransform();
2751 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002752 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002753 bool firstLayer = true;
2754 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2755 const Region clip(dirty.intersect(
2756 displayTransform.transform(layer->visibleRegion)));
2757 ALOGV("Layer: %s", layer->getName().string());
2758 ALOGV(" Composition type: %s",
2759 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002760 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002761 switch (layer->getCompositionType(hwcId)) {
2762 case HWC2::Composition::Cursor:
2763 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002764 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002765 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002766 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002767 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002768 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002769 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002770 // never clear the very first layer since we're
2771 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002772 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002773 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002774 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002775 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002776 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002777 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002778 break;
2779 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002780 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002781 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002782 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002783 } else {
2784 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002785 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002786 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002787 }
2788 } else {
2789 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002790 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002791 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002792 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002793 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002794 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002795 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002796 }
2797 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002798
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002799 if (applyColorMatrix) {
2800 getRenderEngine().setupColorTransform(oldColorMatrix);
2801 }
2802
Mathias Agopianf45c5102012-10-24 16:29:17 -07002803 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002804 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002805 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806}
2807
Fabien Sanglard830b8472016-11-30 16:35:58 -08002808void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2809 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002810 RenderEngine& engine(getRenderEngine());
2811 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812}
2813
Dan Stoza7d89d062015-04-30 13:29:25 -07002814status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002815 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002816 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002817 const sp<Layer>& lbc,
2818 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002819{
Dan Stoza7d89d062015-04-30 13:29:25 -07002820 // add this layer to the current state list
2821 {
2822 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002823 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002824 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2825 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002826 return NO_MEMORY;
2827 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002828 if (parent == nullptr) {
2829 mCurrentState.layersSortedByZ.add(lbc);
2830 } else {
chaviwc9674332017-08-28 12:32:18 -07002831 bool found = false;
2832 mCurrentState.traverseInZOrder([&](Layer* layer) {
2833 if (layer == parent.get()) {
2834 found = true;
2835 }
2836 });
2837
2838 if (!found) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002839 ALOGE("addClientLayer called with a removed parent");
2840 return NAME_NOT_FOUND;
2841 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002842 parent->addChild(lbc);
2843 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002844
Dan Stoza7d89d062015-04-30 13:29:25 -07002845 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002846 mLayersAdded = true;
2847 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002848 }
2849
Mathias Agopian96f08192010-06-02 23:28:45 -07002850 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002851 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002852
Dan Stoza7d89d062015-04-30 13:29:25 -07002853 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002854}
2855
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002856status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002857 Mutex::Autolock _l(mStateLock);
2858
Robert Carr1f0a16a2016-10-24 16:27:39 -07002859 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002860 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002861 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002862 if (topLevelOnly) {
2863 return NO_ERROR;
2864 }
2865
Chia-I Wu98f1c102017-05-30 14:54:08 -07002866 sp<Layer> ancestor = p;
2867 while (ancestor->getParent() != nullptr) {
2868 ancestor = ancestor->getParent();
2869 }
2870 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2871 ALOGE("removeLayer called with a layer whose parent has been removed");
2872 return NAME_NOT_FOUND;
2873 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002874
2875 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002876 } else {
2877 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002878 }
2879
Robert Carr136e2f62017-02-08 17:54:29 -08002880 // As a matter of normal operation, the LayerCleaner will produce a second
2881 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2882 // so we will succeed in promoting it, but it's already been removed
2883 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2884 // otherwise something has gone wrong and we are leaking the layer.
2885 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002886 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2887 layer->getName().string(),
2888 (p != nullptr) ? p->getName().string() : "no-parent");
2889 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002890 } else if (index < 0) {
2891 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002892 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002893
Chia-I Wuc6657022017-08-15 11:18:17 -07002894 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002895 mLayersPendingRemoval.add(layer);
2896 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002897 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002898 setTransactionFlags(eTransactionNeeded);
2899 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002900}
2901
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002902uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002903 return android_atomic_release_load(&mTransactionFlags);
2904}
2905
Mathias Agopian3f844832013-08-07 21:24:32 -07002906uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2908}
2909
Mathias Agopian3f844832013-08-07 21:24:32 -07002910uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002911 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2912 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002913 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914 }
2915 return old;
2916}
2917
Mathias Agopian8b33f032012-07-24 20:43:54 -07002918void SurfaceFlinger::setTransactionState(
2919 const Vector<ComposerState>& state,
2920 const Vector<DisplayState>& displays,
2921 uint32_t flags)
2922{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002923 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002924 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002925 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002926
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002927 if (flags & eAnimation) {
2928 // For window updates that are part of an animation we must wait for
2929 // previous animation "frames" to be handled.
2930 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002931 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002932 if (CC_UNLIKELY(err != NO_ERROR)) {
2933 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002934 // caller after a few seconds.
2935 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2936 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002937 mAnimTransactionPending = false;
2938 break;
2939 }
2940 }
2941 }
2942
Mathias Agopiane57f2922012-08-09 16:29:12 -07002943 size_t count = displays.size();
2944 for (size_t i=0 ; i<count ; i++) {
2945 const DisplayState& s(displays[i]);
2946 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002947 }
2948
Mathias Agopiane57f2922012-08-09 16:29:12 -07002949 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002950 for (size_t i=0 ; i<count ; i++) {
2951 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002952 // Here we need to check that the interface we're given is indeed
2953 // one of our own. A malicious client could give us a NULL
2954 // IInterface, or one of its own or even one of our own but a
2955 // different type. All these situations would cause us to crash.
2956 //
2957 // NOTE: it would be better to use RTTI as we could directly check
2958 // that we have a Client*. however, RTTI is disabled in Android.
2959 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002960 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002961 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002962 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002963 sp<Client> client( static_cast<Client *>(s.client.get()) );
2964 transactionFlags |= setClientStateLocked(client, s.state);
2965 }
2966 }
2967 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002968 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002969
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002970 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2971 // anyway. This can be used as a flush mechanism for previous async transactions.
2972 // Empty animation transaction can be used to simulate back-pressure, so also force a
2973 // transaction for empty animation transactions.
2974 if (transactionFlags == 0 &&
2975 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002976 transactionFlags = eTransactionNeeded;
2977 }
2978
Mathias Agopian386aa982011-11-07 21:58:03 -08002979 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002980 if (mInterceptor.isEnabled()) {
2981 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2982 }
Irvel468051e2016-06-13 16:44:44 -07002983
Mathias Agopian386aa982011-11-07 21:58:03 -08002984 // this triggers the transaction
2985 setTransactionFlags(transactionFlags);
2986
2987 // if this is a synchronous transaction, wait for it to take effect
2988 // before returning.
2989 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002990 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002991 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002992 if (flags & eAnimation) {
2993 mAnimTransactionPending = true;
2994 }
2995 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002996 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2997 if (CC_UNLIKELY(err != NO_ERROR)) {
2998 // just in case something goes wrong in SF, return to the
2999 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003000 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3001 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003002 break;
3003 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003004 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003005 }
3006}
3007
Mathias Agopiane57f2922012-08-09 16:29:12 -07003008uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3009{
Jesse Hall9a143922012-10-04 16:29:19 -07003010 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3011 if (dpyIdx < 0)
3012 return 0;
3013
Mathias Agopiane57f2922012-08-09 16:29:12 -07003014 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003015 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003016 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003017 const uint32_t what = s.what;
3018 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003019 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003020 disp.surface = s.surface;
3021 flags |= eDisplayTransactionNeeded;
3022 }
3023 }
3024 if (what & DisplayState::eLayerStackChanged) {
3025 if (disp.layerStack != s.layerStack) {
3026 disp.layerStack = s.layerStack;
3027 flags |= eDisplayTransactionNeeded;
3028 }
3029 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003030 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003031 if (disp.orientation != s.orientation) {
3032 disp.orientation = s.orientation;
3033 flags |= eDisplayTransactionNeeded;
3034 }
3035 if (disp.frame != s.frame) {
3036 disp.frame = s.frame;
3037 flags |= eDisplayTransactionNeeded;
3038 }
3039 if (disp.viewport != s.viewport) {
3040 disp.viewport = s.viewport;
3041 flags |= eDisplayTransactionNeeded;
3042 }
3043 }
Michael Lentine47e45402014-07-18 15:34:25 -07003044 if (what & DisplayState::eDisplaySizeChanged) {
3045 if (disp.width != s.width) {
3046 disp.width = s.width;
3047 flags |= eDisplayTransactionNeeded;
3048 }
3049 if (disp.height != s.height) {
3050 disp.height = s.height;
3051 flags |= eDisplayTransactionNeeded;
3052 }
3053 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003054 }
3055 return flags;
3056}
3057
3058uint32_t SurfaceFlinger::setClientStateLocked(
3059 const sp<Client>& client,
3060 const layer_state_t& s)
3061{
3062 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003063 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003064 if (layer != 0) {
3065 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003066 bool geometryAppliesWithResize =
3067 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003068 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003069 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003070 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003071 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003072 }
3073 if (what & layer_state_t::eLayerChanged) {
3074 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003075 const auto& p = layer->getParent();
3076 if (p == nullptr) {
3077 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3078 if (layer->setLayer(s.z) && idx >= 0) {
3079 mCurrentState.layersSortedByZ.removeAt(idx);
3080 mCurrentState.layersSortedByZ.add(layer);
3081 // we need traversal (state changed)
3082 // AND transaction (list changed)
3083 flags |= eTransactionNeeded|eTraversalNeeded;
3084 }
3085 } else {
3086 if (p->setChildLayer(layer, s.z)) {
3087 flags |= eTransactionNeeded|eTraversalNeeded;
3088 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003089 }
3090 }
Robert Carrdb66e622017-04-10 16:55:57 -07003091 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003092 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003093 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003094 mCurrentState.layersSortedByZ.removeAt(idx);
3095 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003096 flags |= eTransactionNeeded|eTraversalNeeded;
3097 }
3098 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003099 if (what & layer_state_t::eSizeChanged) {
3100 if (layer->setSize(s.w, s.h)) {
3101 flags |= eTraversalNeeded;
3102 }
3103 }
3104 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003105 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003106 flags |= eTraversalNeeded;
3107 }
chaviw13fdc492017-06-27 12:40:18 -07003108 if (what & layer_state_t::eColorChanged) {
3109 if (layer->setColor(s.color))
3110 flags |= eTraversalNeeded;
3111 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003112 if (what & layer_state_t::eMatrixChanged) {
3113 if (layer->setMatrix(s.matrix))
3114 flags |= eTraversalNeeded;
3115 }
3116 if (what & layer_state_t::eTransparentRegionChanged) {
3117 if (layer->setTransparentRegionHint(s.transparentRegion))
3118 flags |= eTraversalNeeded;
3119 }
Dan Stoza23116082015-06-18 14:58:39 -07003120 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003121 if (layer->setFlags(s.flags, s.mask))
3122 flags |= eTraversalNeeded;
3123 }
3124 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003125 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003126 flags |= eTraversalNeeded;
3127 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003128 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003129 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003130 flags |= eTraversalNeeded;
3131 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003132 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003133 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003134 // We only allow setting layer stacks for top level layers,
3135 // everything else inherits layer stack from its parent.
3136 if (layer->hasParent()) {
3137 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3138 layer->getName().string());
3139 } else if (idx < 0) {
3140 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3141 "that also does not appear in the top level layer list. Something"
3142 " has gone wrong.", layer->getName().string());
3143 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003144 mCurrentState.layersSortedByZ.removeAt(idx);
3145 mCurrentState.layersSortedByZ.add(layer);
3146 // we need traversal (state changed)
3147 // AND transaction (list changed)
3148 flags |= eTransactionNeeded|eTraversalNeeded;
3149 }
3150 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003151 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003152 if (s.barrierHandle != nullptr) {
3153 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3154 } else if (s.barrierGbp != nullptr) {
3155 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3156 if (authenticateSurfaceTextureLocked(gbp)) {
3157 const auto& otherLayer =
3158 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3159 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3160 } else {
3161 ALOGE("Attempt to defer transaction to to an"
3162 " unrecognized GraphicBufferProducer");
3163 }
3164 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003165 // We don't trigger a traversal here because if no other state is
3166 // changed, we don't want this to cause any more work
3167 }
chaviwf1961f72017-09-18 16:41:07 -07003168 if (what & layer_state_t::eReparent) {
3169 if (layer->reparent(s.parentHandleForChild)) {
chaviw06178942017-07-27 10:25:59 -07003170 flags |= eTransactionNeeded|eTraversalNeeded;
3171 }
3172 }
Robert Carr1db73f62016-12-21 12:58:51 -08003173 if (what & layer_state_t::eReparentChildren) {
3174 if (layer->reparentChildren(s.reparentHandle)) {
3175 flags |= eTransactionNeeded|eTraversalNeeded;
3176 }
3177 }
Robert Carr9524cb32017-02-13 11:32:32 -08003178 if (what & layer_state_t::eDetachChildren) {
3179 layer->detachChildren();
3180 }
Robert Carrc3574f72016-03-24 12:19:32 -07003181 if (what & layer_state_t::eOverrideScalingModeChanged) {
3182 layer->setOverrideScalingMode(s.overrideScalingMode);
3183 // We don't trigger a traversal here because if no other state is
3184 // changed, we don't want this to cause any more work
3185 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003186 }
3187 return flags;
3188}
3189
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003190status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003191 const String8& name,
3192 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003193 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003194 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3195 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003197 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003198 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003199 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003200 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003201 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003202
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003203 status_t result = NO_ERROR;
3204
3205 sp<Layer> layer;
3206
Cody Northropbc755282017-03-31 12:00:08 -06003207 String8 uniqueName = getUniqueLayerName(name);
3208
Mathias Agopian3165cc22012-08-08 19:42:09 -07003209 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3210 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003211 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003212 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003213 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 break;
chaviw13fdc492017-06-27 12:40:18 -07003215 case ISurfaceComposerClient::eFXSurfaceColor:
3216 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003217 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003218 handle, gbp, &layer);
3219 break;
3220 default:
3221 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222 break;
3223 }
3224
Dan Stoza7d89d062015-04-30 13:29:25 -07003225 if (result != NO_ERROR) {
3226 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003228
Chia-I Wuab0c3192017-08-01 11:29:00 -07003229 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3230 // TODO b/64227542
3231 if (windowType == 441731) {
3232 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3233 layer->setPrimaryDisplayOnly();
3234 }
3235
Albert Chaulk479c60c2017-01-27 14:21:34 -05003236 layer->setInfo(windowType, ownerUid);
3237
Robert Carr1f0a16a2016-10-24 16:27:39 -07003238 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003239 if (result != NO_ERROR) {
3240 return result;
3241 }
Irvelffc9efc2016-07-27 15:16:37 -07003242 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003243
3244 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003245 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003246}
3247
Cody Northropbc755282017-03-31 12:00:08 -06003248String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3249{
3250 bool matchFound = true;
3251 uint32_t dupeCounter = 0;
3252
3253 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3254 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3255
3256 // Loop over layers until we're sure there is no matching name
3257 while (matchFound) {
3258 matchFound = false;
3259 mDrawingState.traverseInZOrder([&](Layer* layer) {
3260 if (layer->getName() == uniqueName) {
3261 matchFound = true;
3262 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3263 }
3264 });
3265 }
3266
3267 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3268
3269 return uniqueName;
3270}
3271
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003272status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3273 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3274 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003275{
3276 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003277 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278 case PIXEL_FORMAT_TRANSPARENT:
3279 case PIXEL_FORMAT_TRANSLUCENT:
3280 format = PIXEL_FORMAT_RGBA_8888;
3281 break;
3282 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003283 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003284 break;
3285 }
3286
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003287 *outLayer = new Layer(this, client, name, w, h, flags);
3288 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3289 if (err == NO_ERROR) {
3290 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003291 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003292 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003293
3294 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3295 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296}
3297
chaviw13fdc492017-06-27 12:40:18 -07003298status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003299 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3300 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003301{
chaviw13fdc492017-06-27 12:40:18 -07003302 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003303 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003304 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003305 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003306}
3307
Mathias Agopianac9fa422013-02-11 16:40:36 -08003308status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003309{
Robert Carr9524cb32017-02-13 11:32:32 -08003310 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003311 status_t err = NO_ERROR;
3312 sp<Layer> l(client->getLayerUser(handle));
3313 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003314 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003315 err = removeLayer(l);
3316 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3317 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003318 }
3319 return err;
3320}
3321
Mathias Agopian13127d82013-03-05 17:47:11 -08003322status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003323{
Mathias Agopian67106042013-03-14 19:18:13 -07003324 // called by ~LayerCleaner() when all references to the IBinder (handle)
3325 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003326 sp<Layer> l = layer.promote();
3327 if (l == nullptr) {
3328 // The layer has already been removed, carry on
3329 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003330 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003331 // If we have a parent, then we can continue to live as long as it does.
3332 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003333}
3334
Mathias Agopianb60314a2012-04-10 22:09:54 -07003335// ---------------------------------------------------------------------------
3336
Andy McFadden13a082e2012-08-24 10:16:42 -07003337void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003338 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003339 Vector<ComposerState> state;
3340 Vector<DisplayState> displays;
3341 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003342 d.what = DisplayState::eDisplayProjectionChanged |
3343 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003344 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003345 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003346 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003347 d.frame.makeInvalid();
3348 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003349 d.width = 0;
3350 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003351 displays.add(d);
3352 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003353 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3354 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003355
Dan Stoza9e56aa02015-11-02 13:00:03 -08003356 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3357 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003358 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003359
Brian Andersond0010582017-03-07 13:20:31 -08003360 // Use phase of 0 since phase is not known.
3361 // Use latency of 0, which will snap to the ideal latency.
3362 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003363}
3364
3365void SurfaceFlinger::initializeDisplays() {
3366 class MessageScreenInitialized : public MessageBase {
3367 SurfaceFlinger* flinger;
3368 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003369 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003370 virtual bool handler() {
3371 flinger->onInitializeDisplays();
3372 return true;
3373 }
3374 };
3375 sp<MessageBase> msg = new MessageScreenInitialized(this);
3376 postMessageAsync(msg); // we may be called from main thread, use async message
3377}
3378
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003379void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003380 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003381 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3382 this);
3383 int32_t type = hw->getDisplayType();
3384 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003385
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003386 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003387 return;
3388 }
3389
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003390 hw->setPowerMode(mode);
3391 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3392 ALOGW("Trying to set power mode for virtual display");
3393 return;
3394 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003395
Irvelffc9efc2016-07-27 15:16:37 -07003396 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003397 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003398 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3399 if (idx < 0) {
3400 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3401 return;
3402 }
3403 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3404 }
3405
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003406 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003407 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003408 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003409 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3410 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003411 // FIXME: eventthread only knows about the main display right now
3412 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003413 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003414 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003415
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003416 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003417 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003418 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003419
3420 struct sched_param param = {0};
3421 param.sched_priority = 1;
3422 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3423 ALOGW("Couldn't set SCHED_FIFO on display on");
3424 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003425 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003426 // Turn off the display
3427 struct sched_param param = {0};
3428 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3429 ALOGW("Couldn't set SCHED_OTHER on display off");
3430 }
3431
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003432 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003433 disableHardwareVsync(true); // also cancels any in-progress resync
3434
Mathias Agopiancde87a32012-09-13 14:09:01 -07003435 // FIXME: eventthread only knows about the main display right now
3436 mEventThread->onScreenReleased();
3437 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003438
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003439 getHwComposer().setPowerMode(type, mode);
3440 mVisibleRegionsDirty = true;
3441 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003442 } else if (mode == HWC_POWER_MODE_DOZE ||
3443 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003444 // Update display while dozing
3445 getHwComposer().setPowerMode(type, mode);
3446 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3447 // FIXME: eventthread only knows about the main display right now
3448 mEventThread->onScreenAcquired();
3449 resyncToHardwareVsync(true);
3450 }
3451 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3452 // Leave display going to doze
3453 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3454 disableHardwareVsync(true); // also cancels any in-progress resync
3455 // FIXME: eventthread only knows about the main display right now
3456 mEventThread->onScreenReleased();
3457 }
3458 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003459 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003460 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003461 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003462 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003463}
3464
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003465void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3466 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003467 SurfaceFlinger& mFlinger;
3468 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003469 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003470 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003471 MessageSetPowerMode(SurfaceFlinger& flinger,
3472 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3473 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003474 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003475 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003476 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003477 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003478 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003479 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003480 ALOGW("Attempt to set power mode = %d for virtual display",
3481 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003482 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003483 mFlinger.setPowerModeInternal(
3484 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003485 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003486 return true;
3487 }
3488 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003489 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003490 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003491}
3492
3493// ---------------------------------------------------------------------------
3494
Vishnu Nair6a408532017-10-24 09:11:27 -07003495status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003496 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003497
Mathias Agopianbd115332013-04-18 16:41:04 -07003498 IPCThreadState* ipc = IPCThreadState::self();
3499 const int pid = ipc->getCallingPid();
3500 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003501
3502 if (asProto) {
3503 // Return early as SurfaceFlinger does not support dumping sections in proto format
3504 return OK;
3505 }
3506
Mathias Agopianbd115332013-04-18 16:41:04 -07003507 if ((uid != AID_SHELL) &&
3508 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003509 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003510 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003512 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003513 // (this would indicate SF is stuck, but we want to be able to
3514 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003515 status_t err = mStateLock.timedLock(s2ns(1));
3516 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003517 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003518 result.appendFormat(
3519 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3520 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003521 }
3522
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003523 bool dumpAll = true;
3524 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003525 size_t numArgs = args.size();
3526 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003527 if ((index < numArgs) &&
3528 (args[index] == String16("--list"))) {
3529 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003530 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003531 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003532 }
3533
3534 if ((index < numArgs) &&
3535 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003536 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003537 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003538 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003539 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003540
3541 if ((index < numArgs) &&
3542 (args[index] == String16("--latency-clear"))) {
3543 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003544 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003545 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003546 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003547
3548 if ((index < numArgs) &&
3549 (args[index] == String16("--dispsync"))) {
3550 index++;
3551 mPrimaryDispSync.dump(result);
3552 dumpAll = false;
3553 }
Dan Stozab90cf072015-03-05 11:05:59 -08003554
3555 if ((index < numArgs) &&
3556 (args[index] == String16("--static-screen"))) {
3557 index++;
3558 dumpStaticScreenStats(result);
3559 dumpAll = false;
3560 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003561
3562 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003563 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003564 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003565 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003566 dumpAll = false;
3567 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003568
3569 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3570 index++;
3571 dumpWideColorInfo(result);
3572 dumpAll = false;
3573 }
chaviw1d044282017-09-27 12:19:28 -07003574
3575 if ((index < numArgs) && (args[index] == String16("--proto"))) {
3576 index++;
3577 LayersProto layersProto = dumpProtoInfo();
3578 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3579 dumpAll = false;
3580 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003581 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003582
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003583 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003584 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003585 }
3586
Mathias Agopian9795c422009-08-26 16:36:26 -07003587 if (locked) {
3588 mStateLock.unlock();
3589 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590 }
3591 write(fd, result.string(), result.size());
3592 return NO_ERROR;
3593}
3594
Dan Stozac7014012014-02-14 15:03:43 -08003595void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3596 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003597{
Robert Carr2047fae2016-11-28 14:09:09 -08003598 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003599 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003600 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003601}
3602
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003603void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003604 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003605{
3606 String8 name;
3607 if (index < args.size()) {
3608 name = String8(args[index]);
3609 index++;
3610 }
3611
Dan Stoza9e56aa02015-11-02 13:00:03 -08003612 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3613 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003614 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003615
3616 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003617 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003618 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003619 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003620 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003621 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003622 }
Robert Carr2047fae2016-11-28 14:09:09 -08003623 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003624 }
3625}
3626
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003627void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003628 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003629{
3630 String8 name;
3631 if (index < args.size()) {
3632 name = String8(args[index]);
3633 index++;
3634 }
3635
Robert Carr2047fae2016-11-28 14:09:09 -08003636 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003637 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003638 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003639 }
Robert Carr2047fae2016-11-28 14:09:09 -08003640 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003641
Svetoslavd85084b2014-03-20 10:28:31 -07003642 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003643}
3644
Jamie Gennis6547ff42013-07-16 20:12:42 -07003645// This should only be called from the main thread. Otherwise it would need
3646// the lock and should use mCurrentState rather than mDrawingState.
3647void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003648 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003649 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003650 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003651
3652 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3653}
3654
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003655void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003656{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003657 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003658 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3659
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003660 if (isLayerTripleBufferingDisabled())
3661 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003662
3663 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003664 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003665 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003666 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003667 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3668 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003669 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003670}
3671
Dan Stozab90cf072015-03-05 11:05:59 -08003672void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3673{
3674 result.appendFormat("Static screen stats:\n");
3675 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3676 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3677 float percent = 100.0f *
3678 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3679 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3680 b + 1, bucketTimeSec, percent);
3681 }
3682 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3683 float percent = 100.0f *
3684 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3685 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3686 NUM_BUCKETS - 1, bucketTimeSec, percent);
3687}
3688
Dan Stozae77c7662016-05-13 11:37:28 -07003689void SurfaceFlinger::recordBufferingStats(const char* layerName,
3690 std::vector<OccupancyTracker::Segment>&& history) {
3691 Mutex::Autolock lock(mBufferingStatsMutex);
3692 auto& stats = mBufferingStats[layerName];
3693 for (const auto& segment : history) {
3694 if (!segment.usedThirdBuffer) {
3695 stats.twoBufferTime += segment.totalTime;
3696 }
3697 if (segment.occupancyAverage < 1.0f) {
3698 stats.doubleBufferedTime += segment.totalTime;
3699 } else if (segment.occupancyAverage < 2.0f) {
3700 stats.tripleBufferedTime += segment.totalTime;
3701 }
3702 ++stats.numSegments;
3703 stats.totalTime += segment.totalTime;
3704 }
3705}
3706
Brian Andersond6927fb2016-07-23 23:37:30 -07003707void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3708 result.appendFormat("Layer frame timestamps:\n");
3709
3710 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3711 const size_t count = currentLayers.size();
3712 for (size_t i=0 ; i<count ; i++) {
3713 currentLayers[i]->dumpFrameEvents(result);
3714 }
3715}
3716
Dan Stozae77c7662016-05-13 11:37:28 -07003717void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3718 result.append("Buffering stats:\n");
3719 result.append(" [Layer name] <Active time> <Two buffer> "
3720 "<Double buffered> <Triple buffered>\n");
3721 Mutex::Autolock lock(mBufferingStatsMutex);
3722 typedef std::tuple<std::string, float, float, float> BufferTuple;
3723 std::map<float, BufferTuple, std::greater<float>> sorted;
3724 for (const auto& statsPair : mBufferingStats) {
3725 const char* name = statsPair.first.c_str();
3726 const BufferingStats& stats = statsPair.second;
3727 if (stats.numSegments == 0) {
3728 continue;
3729 }
3730 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3731 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3732 stats.totalTime;
3733 float doubleBufferRatio = static_cast<float>(
3734 stats.doubleBufferedTime) / stats.totalTime;
3735 float tripleBufferRatio = static_cast<float>(
3736 stats.tripleBufferedTime) / stats.totalTime;
3737 sorted.insert({activeTime, {name, twoBufferRatio,
3738 doubleBufferRatio, tripleBufferRatio}});
3739 }
3740 for (const auto& sortedPair : sorted) {
3741 float activeTime = sortedPair.first;
3742 const BufferTuple& values = sortedPair.second;
3743 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3744 std::get<0>(values).c_str(), activeTime,
3745 std::get<1>(values), std::get<2>(values),
3746 std::get<3>(values));
3747 }
3748 result.append("\n");
3749}
3750
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003751void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3752 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003753 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003754
3755 // TODO: print out if wide-color mode is active or not
3756
3757 for (size_t d = 0; d < mDisplays.size(); d++) {
3758 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3759 int32_t hwcId = displayDevice->getHwcDisplayId();
3760 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3761 continue;
3762 }
3763
3764 result.appendFormat("Display %d color modes:\n", hwcId);
3765 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3766 for (auto&& mode : modes) {
3767 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3768 }
3769
3770 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3771 result.appendFormat(" Current color mode: %s (%d)\n",
3772 decodeColorMode(currentMode).c_str(), currentMode);
3773 }
3774 result.append("\n");
3775}
3776
chaviw1d044282017-09-27 12:19:28 -07003777LayersProto SurfaceFlinger::dumpProtoInfo() const {
3778 LayersProto layersProto;
3779 mCurrentState.traverseInZOrder([&](Layer* layer) {
3780 LayerProto* layerProto = layersProto.add_layers();
3781 layer->writeToProto(layerProto, LayerVector::StateSet::Current);
3782 });
3783
3784 return layersProto;
3785}
3786
Mathias Agopian74d211a2013-04-22 16:55:35 +02003787void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3788 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003789{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003790 bool colorize = false;
3791 if (index < args.size()
3792 && (args[index] == String16("--color"))) {
3793 colorize = true;
3794 index++;
3795 }
3796
3797 Colorizer colorizer(colorize);
3798
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003799 // figure out if we're stuck somewhere
3800 const nsecs_t now = systemTime();
3801 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3802 const nsecs_t inTransaction(mDebugInTransaction);
3803 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3804 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3805
3806 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003807 * Dump library configuration.
3808 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003809
3810 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003811 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003812 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003813 appendSfConfigString(result);
3814 appendUiConfigString(result);
3815 appendGuiConfigString(result);
3816 result.append("\n");
3817
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003818 result.append("\nWide-Color information:\n");
3819 dumpWideColorInfo(result);
3820
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003821 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003822 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003823 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003824 result.append(SyncFeatures::getInstance().toString());
3825 result.append("\n");
3826
Dan Stoza9e56aa02015-11-02 13:00:03 -08003827 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3828
Andy McFadden41d67d72014-04-25 16:58:34 -07003829 colorizer.bold(result);
3830 result.append("DispSync configuration: ");
3831 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003832 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003833 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003834 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003835 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003836 result.append("\n");
3837
Dan Stozab90cf072015-03-05 11:05:59 -08003838 // Dump static screen stats
3839 result.append("\n");
3840 dumpStaticScreenStats(result);
3841 result.append("\n");
3842
Dan Stozae77c7662016-05-13 11:37:28 -07003843 dumpBufferingStats(result);
3844
Andy McFadden4803b742012-09-24 19:07:20 -07003845 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003846 * Dump the visible layer list
3847 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003848 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003849 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003850 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003851
3852 LayersProto layersProto = dumpProtoInfo();
3853 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3854 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003855
3856 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003857 * Dump Display state
3858 */
3859
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003860 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003861 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003862 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003863 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3864 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003865 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003866 }
3867
3868 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003869 * Dump SurfaceFlinger global state
3870 */
3871
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003872 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003873 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003874 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003875
Mathias Agopian888c8222012-08-04 21:10:38 -07003876 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003877 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003878
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003879 colorizer.bold(result);
3880 result.appendFormat("EGL implementation : %s\n",
3881 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3882 colorizer.reset(result);
3883 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003884 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003885
Mathias Agopian875d8e12013-06-07 15:35:48 -07003886 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003887
Mathias Agopian42977342012-08-05 00:40:46 -07003888 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003889 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3890 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003891 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003892 " last eglSwapBuffers() time: %f us\n"
3893 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003894 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003895 " refresh-rate : %f fps\n"
3896 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003897 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003898 " gpu_to_cpu_unsupported : %d\n"
3899 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003900 mLastSwapBufferTime/1000.0,
3901 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003902 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003903 1e9 / activeConfig->getVsyncPeriod(),
3904 activeConfig->getDpiX(),
3905 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003906 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003907
Mathias Agopian74d211a2013-04-22 16:55:35 +02003908 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003909 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003910
Mathias Agopian74d211a2013-04-22 16:55:35 +02003911 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003912 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003913
3914 /*
3915 * VSYNC state
3916 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003917 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003918 result.append("\n");
3919
3920 /*
3921 * HWC layer minidump
3922 */
3923 for (size_t d = 0; d < mDisplays.size(); d++) {
3924 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3925 int32_t hwcId = displayDevice->getHwcDisplayId();
3926 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3927 continue;
3928 }
3929
3930 result.appendFormat("Display %d HWC layers:\n", hwcId);
3931 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003932 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003933 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003934 });
Dan Stozae22aec72016-08-01 13:20:59 -07003935 result.append("\n");
3936 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003937
3938 /*
3939 * Dump HWComposer state
3940 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003941 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003942 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003943 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003944 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003945 result.appendFormat(" h/w composer %s\n",
3946 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003947 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003948
3949 /*
3950 * Dump gralloc state
3951 */
3952 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3953 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003954
3955 /*
3956 * Dump VrFlinger state if in use.
3957 */
3958 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3959 result.append("VrFlinger state:\n");
3960 result.append(mVrFlinger->Dump().c_str());
3961 result.append("\n");
3962 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003963}
3964
Mathias Agopian13127d82013-03-05 17:47:11 -08003965const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003966SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003967 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003968 wp<IBinder> dpy;
3969 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3970 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3971 dpy = mDisplays.keyAt(i);
3972 break;
3973 }
3974 }
3975 if (dpy == NULL) {
3976 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3977 // Just use the primary display so we have something to return
3978 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3979 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003980 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003981}
3982
Keun young Park63f165f2012-08-31 10:53:36 -07003983bool SurfaceFlinger::startDdmConnection()
3984{
3985 void* libddmconnection_dso =
3986 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3987 if (!libddmconnection_dso) {
3988 return false;
3989 }
3990 void (*DdmConnection_start)(const char* name);
3991 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003992 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003993 if (!DdmConnection_start) {
3994 dlclose(libddmconnection_dso);
3995 return false;
3996 }
3997 (*DdmConnection_start)(getServiceName());
3998 return true;
3999}
4000
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004001status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004002 switch (code) {
4003 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004004 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004005 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004006 case CLEAR_ANIMATION_FRAME_STATS:
4007 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004008 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004009 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004010 case ENABLE_VSYNC_INJECTIONS:
4011 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004012 {
4013 // codes that require permission check
4014 IPCThreadState* ipc = IPCThreadState::self();
4015 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004016 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004017 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004018 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004019 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004020 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004021 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004022 break;
4023 }
Robert Carr1db73f62016-12-21 12:58:51 -08004024 /*
4025 * Calling setTransactionState is safe, because you need to have been
4026 * granted a reference to Client* and Handle* to do anything with it.
4027 *
4028 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4029 */
4030 case SET_TRANSACTION_STATE:
4031 case CREATE_SCOPED_CONNECTION:
4032 {
4033 return OK;
4034 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004035 case CAPTURE_SCREEN:
4036 {
4037 // codes that require permission check
4038 IPCThreadState* ipc = IPCThreadState::self();
4039 const int pid = ipc->getCallingPid();
4040 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004041 if ((uid != AID_GRAPHICS) &&
4042 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004043 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004044 return PERMISSION_DENIED;
4045 }
4046 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004047 }
chaviwa76b2712017-09-20 12:02:26 -07004048 case CAPTURE_LAYERS: {
4049 IPCThreadState* ipc = IPCThreadState::self();
4050 const int pid = ipc->getCallingPid();
4051 const int uid = ipc->getCallingUid();
4052 if ((uid != AID_GRAPHICS) &&
4053 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4054 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4055 return PERMISSION_DENIED;
4056 }
4057 break;
4058 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004059 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004060 return OK;
4061}
4062
4063status_t SurfaceFlinger::onTransact(
4064 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4065{
4066 status_t credentialCheck = CheckTransactCodeCredentials(code);
4067 if (credentialCheck != OK) {
4068 return credentialCheck;
4069 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004070
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004071 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4072 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004073 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004074 IPCThreadState* ipc = IPCThreadState::self();
4075 const int uid = ipc->getCallingUid();
4076 if (CC_UNLIKELY(uid != AID_SYSTEM
4077 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004078 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004079 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004080 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004081 return PERMISSION_DENIED;
4082 }
4083 int n;
4084 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004085 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004086 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004087 return NO_ERROR;
4088 case 1002: // SHOW_UPDATES
4089 n = data.readInt32();
4090 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004091 invalidateHwcGeometry();
4092 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004093 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004094 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004095 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004096 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004097 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004098 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004099 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004100 setTransactionFlags(
4101 eTransactionNeeded|
4102 eDisplayTransactionNeeded|
4103 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004104 return NO_ERROR;
4105 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004106 case 1006:{ // send empty update
4107 signalRefresh();
4108 return NO_ERROR;
4109 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004110 case 1008: // toggle use of hw composer
4111 n = data.readInt32();
4112 mDebugDisableHWC = n ? 1 : 0;
4113 invalidateHwcGeometry();
4114 repaintEverything();
4115 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004116 case 1009: // toggle use of transform hint
4117 n = data.readInt32();
4118 mDebugDisableTransformHint = n ? 1 : 0;
4119 invalidateHwcGeometry();
4120 repaintEverything();
4121 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004122 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004123 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004124 reply->writeInt32(0);
4125 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004126 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004127 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004128 return NO_ERROR;
4129 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004130 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004131 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004132 return NO_ERROR;
4133 }
4134 case 1014: {
4135 // daltonize
4136 n = data.readInt32();
4137 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004138 case 1:
4139 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4140 break;
4141 case 2:
4142 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4143 break;
4144 case 3:
4145 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4146 break;
4147 default:
4148 mDaltonizer.setType(ColorBlindnessType::None);
4149 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004150 }
4151 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004152 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004153 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004154 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004155 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004156 invalidateHwcGeometry();
4157 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004158 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004159 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004160 case 1015: {
4161 // apply a color matrix
4162 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004163 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004164 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004165 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004166 for (size_t j = 0; j < 4; j++) {
4167 mColorMatrix[i][j] = data.readFloat();
4168 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004169 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004170 } else {
4171 mColorMatrix = mat4();
4172 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004173
4174 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4175 // the division by w in the fragment shader
4176 float4 lastRow(transpose(mColorMatrix)[3]);
4177 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4178 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4179 }
4180
Alan Viverette9c5a3332013-09-12 20:04:35 -07004181 invalidateHwcGeometry();
4182 repaintEverything();
4183 return NO_ERROR;
4184 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004185 // This is an experimental interface
4186 // Needs to be shifted to proper binder interface when we productize
4187 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004188 n = data.readInt32();
4189 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004190 return NO_ERROR;
4191 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004192 case 1017: {
4193 n = data.readInt32();
4194 mForceFullDamage = static_cast<bool>(n);
4195 return NO_ERROR;
4196 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004197 case 1018: { // Modify Choreographer's phase offset
4198 n = data.readInt32();
4199 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4200 return NO_ERROR;
4201 }
4202 case 1019: { // Modify SurfaceFlinger's phase offset
4203 n = data.readInt32();
4204 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4205 return NO_ERROR;
4206 }
Irvel468051e2016-06-13 16:44:44 -07004207 case 1020: { // Layer updates interceptor
4208 n = data.readInt32();
4209 if (n) {
4210 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004211 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004212 }
4213 else{
4214 ALOGV("Interceptor disabled");
4215 mInterceptor.disable();
4216 }
4217 return NO_ERROR;
4218 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004219 case 1021: { // Disable HWC virtual displays
4220 n = data.readInt32();
4221 mUseHwcVirtualDisplays = !n;
4222 return NO_ERROR;
4223 }
Romain Guy0147a172017-06-01 13:53:56 -07004224 case 1022: { // Set saturation boost
4225 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4226
4227 invalidateHwcGeometry();
4228 repaintEverything();
4229 return NO_ERROR;
4230 }
Romain Guy54f154a2017-10-24 21:40:32 +01004231 case 1023: { // Set native mode
4232 mForceNativeColorMode = data.readInt32() == 1;
4233
4234 invalidateHwcGeometry();
4235 repaintEverything();
4236 return NO_ERROR;
4237 }
4238 case 1024: { // Is wide color gamut rendering/color management supported?
4239 reply->writeBool(hasWideColorDisplay);
4240 return NO_ERROR;
4241 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004242 case 1025: { // tracing
4243 n = data.readInt32();
4244 if (n) {
4245 ALOGV("LayerTracing enabled");
4246 mTracing.enable();
4247 doTracing("tracing.enable");
4248 reply->writeInt32(NO_ERROR);
4249 } else {
4250 ALOGV("LayerTracing disabled");
4251 status_t err = mTracing.disable();
4252 reply->writeInt32(err);
4253 }
4254 return NO_ERROR;
4255 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004256 }
4257 }
4258 return err;
4259}
4260
Steven Thomas6d8110b2017-08-31 18:24:21 -07004261void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004262 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004263 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004264}
4265
Steven Thomas6d8110b2017-08-31 18:24:21 -07004266void SurfaceFlinger::repaintEverything() {
4267 ConditionalLock _l(mStateLock,
4268 std::this_thread::get_id() != mMainThreadId);
4269 repaintEverythingLocked();
4270}
4271
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004272// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4273class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004274public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004275 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4276 ~WindowDisconnector() {
4277 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004278 }
4279
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004280private:
4281 ANativeWindow* mWindow;
4282 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004283};
4284
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004285static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4286 uint32_t requestedHeight, bool hasWideColorDisplay,
4287 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4288 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4289 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4290
4291 int err = 0;
4292 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4293 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4294 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4295 err |= native_window_set_usage(window, usage);
4296
4297 if (hasWideColorDisplay) {
4298 err |= native_window_set_buffers_data_space(window,
4299 renderEngineUsesWideColor
4300 ? HAL_DATASPACE_DISPLAY_P3
4301 : HAL_DATASPACE_V0_SRGB);
4302 }
4303
4304 if (err != NO_ERROR) {
4305 return BAD_VALUE;
4306 }
4307
4308 /* TODO: Once we have the sync framework everywhere this can use
4309 * server-side waits on the fence that dequeueBuffer returns.
4310 */
4311 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4312 if (err != NO_ERROR) {
4313 return err;
4314 }
4315
4316 return NO_ERROR;
4317}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004318
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004319status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
chaviwa76b2712017-09-20 12:02:26 -07004320 const sp<IGraphicBufferProducer>& producer, Rect sourceCrop,
4321 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4322 int32_t maxLayerZ, bool useIdentityTransform,
4323 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004324 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004325
chaviwa76b2712017-09-20 12:02:26 -07004326 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4327
4328 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4329 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4330
4331 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4332 device, minLayerZ, maxLayerZ, std::placeholders::_1);
4333 return captureScreenCommon(renderArea, traverseLayers, producer, useIdentityTransform);
4334}
4335
4336status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
4337 const sp<IGraphicBufferProducer>& producer,
4338 ISurfaceComposer::Rotation rotation) {
4339 ATRACE_CALL();
4340
4341 class LayerRenderArea : public RenderArea {
4342 public:
4343 LayerRenderArea(const sp<Layer>& layer, ISurfaceComposer::Rotation rotation)
4344 : RenderArea(layer->getCurrentState().active.h, layer->getCurrentState().active.w,
4345 rotation),
4346 mLayer(layer) {}
4347 const Transform& getTransform() const override {
4348 // Make the top level transform the inverse the transform and it's parent so it sets
4349 // the whole capture back to 0,0
4350 return *new Transform(mLayer->getTransform().inverse());
4351 }
4352 Rect getBounds() const override {
4353 const Layer::State& layerState(mLayer->getDrawingState());
4354 return Rect(layerState.active.w, layerState.active.h);
4355 }
4356 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4357 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4358 bool isSecure() const override { return false; }
4359 bool needsFiltering() const override { return false; }
4360
4361 Rect getSourceCrop() const override { return getBounds(); }
4362 bool getWideColorSupport() const override { return false; }
4363 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4364
4365 private:
4366 const sp<Layer>& mLayer;
4367 };
4368
4369 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4370 auto parent = layerHandle->owner.promote();
4371
4372 LayerRenderArea renderArea(parent, rotation);
4373 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4374 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4375 if (!layer->isVisible()) {
4376 return;
4377 }
4378 visitor(layer);
4379 });
4380 };
4381 return captureScreenCommon(renderArea, traverseLayers, producer, false);
4382}
4383
4384status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4385 TraverseLayersFunction traverseLayers,
4386 const sp<IGraphicBufferProducer>& producer,
4387 bool useIdentityTransform) {
4388 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004389
4390 if (CC_UNLIKELY(producer == 0))
4391 return BAD_VALUE;
4392
chaviwa76b2712017-09-20 12:02:26 -07004393 renderArea.updateDimensions();
4394
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004395 // if we have secure windows on this display, never allow the screen capture
4396 // unless the producer interface is local (i.e.: we can take a screenshot for
4397 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004398 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004399
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004400 // create a surface (because we're a producer, and we need to
4401 // dequeue/queue a buffer)
4402 sp<Surface> surface = new Surface(producer, false);
4403
4404 // Put the screenshot Surface into async mode so that
4405 // Layer::headFenceHasSignaled will always return true and we'll latch the
4406 // first buffer regardless of whether or not its acquire fence has
4407 // signaled. This is needed to avoid a race condition in the rotation
4408 // animation. See b/30209608
4409 surface->setAsyncMode(true);
4410
4411 ANativeWindow* window = surface.get();
4412
4413 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4414 if (result != NO_ERROR) {
4415 return result;
4416 }
4417 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4418
4419 ANativeWindowBuffer* buffer = nullptr;
chaviwa76b2712017-09-20 12:02:26 -07004420 result = getWindowBuffer(window, renderArea.getReqWidth(), renderArea.getReqHeight(),
4421 hasWideColorDisplay && !mForceNativeColorMode,
4422 getRenderEngine().usesWideColor(), &buffer);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004423 if (result != NO_ERROR) {
4424 return result;
4425 }
4426
4427 // This mutex protects syncFd and captureResult for communication of the return values from the
4428 // main thread back to this Binder thread
4429 std::mutex captureMutex;
4430 std::condition_variable captureCondition;
4431 std::unique_lock<std::mutex> captureLock(captureMutex);
4432 int syncFd = -1;
4433 std::optional<status_t> captureResult;
4434
4435 sp<LambdaMessage> message = new LambdaMessage([&]() {
4436 // If there is a refresh pending, bug out early and tell the binder thread to try again
4437 // after the refresh.
4438 if (mRefreshPending) {
4439 ATRACE_NAME("Skipping screenshot for now");
4440 std::unique_lock<std::mutex> captureLock(captureMutex);
4441 captureResult = std::make_optional<status_t>(EAGAIN);
4442 captureCondition.notify_one();
4443 return;
4444 }
4445
4446 status_t result = NO_ERROR;
4447 int fd = -1;
4448 {
4449 Mutex::Autolock _l(mStateLock);
chaviwa76b2712017-09-20 12:02:26 -07004450 result = captureScreenImplLocked(renderArea, traverseLayers, buffer,
4451 useIdentityTransform, isLocalScreenshot, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004452 }
4453
4454 {
4455 std::unique_lock<std::mutex> captureLock(captureMutex);
4456 syncFd = fd;
4457 captureResult = std::make_optional<status_t>(result);
4458 captureCondition.notify_one();
4459 }
4460 });
4461
4462 result = postMessageAsync(message);
4463 if (result == NO_ERROR) {
4464 captureCondition.wait(captureLock, [&]() { return captureResult; });
4465 while (*captureResult == EAGAIN) {
4466 captureResult.reset();
4467 result = postMessageAsync(message);
4468 if (result != NO_ERROR) {
4469 return result;
4470 }
4471 captureCondition.wait(captureLock, [&]() { return captureResult; });
4472 }
4473 result = *captureResult;
4474 }
4475
4476 if (result == NO_ERROR) {
4477 // queueBuffer takes ownership of syncFd
4478 result = window->queueBuffer(window, buffer, syncFd);
4479 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004480 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004481}
4482
chaviwa76b2712017-09-20 12:02:26 -07004483void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4484 TraverseLayersFunction traverseLayers, bool yswap,
4485 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004486 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004487
Mathias Agopian3f844832013-08-07 21:24:32 -07004488 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004489
4490 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004491 const auto raWidth = renderArea.getWidth();
4492 const auto raHeight = renderArea.getHeight();
4493
4494 const auto reqWidth = renderArea.getReqWidth();
4495 const auto reqHeight = renderArea.getReqHeight();
4496 Rect sourceCrop = renderArea.getSourceCrop();
4497
4498 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4499 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004500
Dan Stozac1879002014-05-22 15:59:05 -07004501 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004502 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004503 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004504 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004505 }
4506
4507 // ensure that sourceCrop is inside screen
4508 if (sourceCrop.left < 0) {
4509 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4510 }
chaviwa76b2712017-09-20 12:02:26 -07004511 if (sourceCrop.right > raWidth) {
4512 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004513 }
4514 if (sourceCrop.top < 0) {
4515 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4516 }
chaviwa76b2712017-09-20 12:02:26 -07004517 if (sourceCrop.bottom > raHeight) {
4518 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004519 }
4520
chaviwa76b2712017-09-20 12:02:26 -07004521 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
4522 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004523
Mathias Agopian180f10d2013-04-10 22:55:41 -07004524 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004525 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004526
4527 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004528 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4529 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004530 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004531
4532 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004533 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004534
chaviwa76b2712017-09-20 12:02:26 -07004535 traverseLayers([&](Layer* layer) {
4536 if (filtering) layer->setFiltering(true);
4537 layer->draw(renderArea, useIdentityTransform);
4538 if (filtering) layer->setFiltering(false);
4539 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004540}
4541
Dan Stozaabcda352017-06-01 14:37:39 -07004542// A simple RAII class that holds an EGLImage and destroys it either:
4543// a) When the destroy() method is called
4544// b) When the object goes out of scope
4545class ImageHolder {
4546public:
4547 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4548 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004549
Dan Stozaabcda352017-06-01 14:37:39 -07004550 void destroy() {
4551 if (mImage != EGL_NO_IMAGE_KHR) {
4552 eglDestroyImageKHR(mDisplay, mImage);
4553 mImage = EGL_NO_IMAGE_KHR;
4554 }
4555 }
4556
4557private:
4558 const EGLDisplay mDisplay;
4559 EGLImageKHR mImage;
4560};
4561
chaviwa76b2712017-09-20 12:02:26 -07004562status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4563 TraverseLayersFunction traverseLayers,
4564 ANativeWindowBuffer* buffer,
4565 bool useIdentityTransform, bool isLocalScreenshot,
4566 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004567 ATRACE_CALL();
4568
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004569 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004570
4571 traverseLayers([&](Layer* layer) {
4572 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4573 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004574
4575 if (!isLocalScreenshot && secureLayerIsVisible) {
4576 ALOGW("FB is protected: PERMISSION_DENIED");
4577 return PERMISSION_DENIED;
4578 }
4579
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004580 int syncFd = -1;
4581 // create an EGLImage from the buffer so we can later
4582 // turn it into a texture
4583 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4584 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4585 if (image == EGL_NO_IMAGE_KHR) {
4586 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004587 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004588
Dan Stozaabcda352017-06-01 14:37:39 -07004589 // This will automatically destroy the image if we return before calling its destroy method
4590 ImageHolder imageHolder(mEGLDisplay, image);
4591
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004592 // this binds the given EGLImage as a framebuffer for the
4593 // duration of this scope.
4594 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004595 if (imageBond.getStatus() != NO_ERROR) {
4596 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004597 return INVALID_OPERATION;
4598 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004599
Dan Stozaabcda352017-06-01 14:37:39 -07004600 // this will in fact render into our dequeued buffer
4601 // via an FBO, which means we didn't have to create
4602 // an EGLSurface and therefore we're not
4603 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004604 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004605
Dan Stozaabcda352017-06-01 14:37:39 -07004606 // Attempt to create a sync khr object that can produce a sync point. If that
4607 // isn't available, create a non-dupable sync object in the fallback path and
4608 // wait on it directly.
4609 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4610 if (!DEBUG_SCREENSHOTS) {
4611 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4612 // native fence fd will not be populated until flush() is done.
4613 getRenderEngine().flush();
4614 }
4615
4616 if (sync != EGL_NO_SYNC_KHR) {
4617 // get the sync fd
4618 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4619 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4620 ALOGW("captureScreen: failed to dup sync khr object");
4621 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004622 }
Dan Stozaabcda352017-06-01 14:37:39 -07004623 eglDestroySyncKHR(mEGLDisplay, sync);
4624 } else {
4625 // fallback path
4626 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004627 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004628 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4629 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4630 EGLint eglErr = eglGetError();
4631 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4632 ALOGW("captureScreen: fence wait timed out");
4633 } else {
4634 ALOGW_IF(eglErr != EGL_SUCCESS,
4635 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004636 }
4637 eglDestroySyncKHR(mEGLDisplay, sync);
4638 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004639 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004640 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004641 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004642 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004643
4644 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004645 const auto reqWidth = renderArea.getReqWidth();
4646 const auto reqHeight = renderArea.getReqHeight();
4647
Dan Stozaabcda352017-06-01 14:37:39 -07004648 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4649 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004650 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004651 delete [] pixels;
4652 }
4653
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004654 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004655 imageHolder.destroy();
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004656 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004657}
4658
Mathias Agopiand5556842013-09-19 17:08:37 -07004659void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004660 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004661 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004662 for (size_t y = 0; y < h; y++) {
4663 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4664 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004665 if (p[x] != 0xFF000000) return;
4666 }
4667 }
chaviwa76b2712017-09-20 12:02:26 -07004668 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004669
Robert Carr2047fae2016-11-28 14:09:09 -08004670 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004671 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004672 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004673 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4674 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4675 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4676 static_cast<float>(state.color.a));
4677 i++;
4678 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004679 }
4680}
4681
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004682// ---------------------------------------------------------------------------
4683
Dan Stoza412903f2017-04-27 13:42:17 -07004684void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4685 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004686}
4687
Dan Stoza412903f2017-04-27 13:42:17 -07004688void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4689 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004690}
4691
chaviwa76b2712017-09-20 12:02:26 -07004692void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4693 int32_t maxLayerZ,
4694 const LayerVector::Visitor& visitor) {
4695 // We loop through the first level of layers without traversing,
4696 // as we need to interpret min/max layer Z in the top level Z space.
4697 for (const auto& layer : mDrawingState.layersSortedByZ) {
4698 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4699 continue;
4700 }
4701 const Layer::State& state(layer->getDrawingState());
4702 if (state.z < minLayerZ || state.z > maxLayerZ) {
4703 continue;
4704 }
4705 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4706 if (!layer->isVisible()) {
4707 return;
4708 }
4709 visitor(layer);
4710 });
4711 }
4712}
4713
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004714}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004715
4716
4717#if defined(__gl_h_)
4718#error "don't include gl/gl.h in this file"
4719#endif
4720
4721#if defined(__gl2_h_)
4722#error "don't include gl2/gl2.h in this file"
4723#endif