blob: 05c76fce4684cbd737f68aa23a586774f7b51d9e [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
31#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080040#include <dvr/vr_flinger.h>
41
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060042#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070044#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070045
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080049#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080050#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051
52#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080055
Mathias Agopiancde87a32012-09-13 14:09:01 -070056#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/String8.h>
58#include <utils/String16.h>
59#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070060#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian921e6ac2012-07-23 23:11:29 -070063#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070064#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070070#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
chaviw13fdc492017-06-27 12:40:18 -070076#include "ColorLayer.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
Jiyong Park00b15b82017-08-10 20:30:56 +0900103extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
Mathias Agopianca088332013-03-28 17:44:13 -0700104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700106
Jaesoo Lee43518572017-01-23 19:03:16 +0900107using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108using namespace android::hardware::configstore::V1_0;
109
Steven Thomasb02664d2017-07-26 18:48:28 -0700110namespace {
111class ConditionalLock {
112public:
113 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
114 if (lock) {
115 mMutex.lock();
116 }
117 }
118 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
119private:
120 Mutex& mMutex;
121 bool mLocked;
122};
123} // namespace anonymous
124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125// ---------------------------------------------------------------------------
126
Mathias Agopian99b49842011-06-27 16:05:52 -0700127const String16 sHardwareTest("android.permission.HARDWARE_TEST");
128const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
129const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
130const String16 sDump("android.permission.DUMP");
131
132// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800133int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
134int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700135bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700136int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700137bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800138uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800139bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800140bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800141int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600142bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700143
Kalle Raitaa099a242017-01-11 11:17:29 -0800144
145std::string getHwcServiceName() {
146 char value[PROPERTY_VALUE_MAX] = {};
147 property_get("debug.sf.hwc_service_name", value, "default");
148 ALOGI("Using HWComposer service: '%s'", value);
149 return std::string(value);
150}
151
152bool useTrebleTestingOverride() {
153 char value[PROPERTY_VALUE_MAX] = {};
154 property_get("debug.sf.treble_testing_override", value, "false");
155 ALOGI("Treble testing override: '%s'", value);
156 return std::string(value) == "true";
157}
158
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700160 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700162 mTransactionPending(false),
163 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700164 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700165 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700166 mRepaintEverything(0),
Kalle Raitaa099a242017-01-11 11:17:29 -0800167 mHwcServiceName(getHwcServiceName()),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800168 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800170 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800171 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800172 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800173 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700175 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700176 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700177 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700178 mDebugInSwapBuffers(0),
179 mLastSwapBufferTime(0),
180 mDebugInTransaction(0),
181 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700182 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700183 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800184 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000185 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700186 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700187 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700188 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800189 mHasPoweredOff(false),
190 mFrameBuckets(),
191 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700192 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800193 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700194 mVrFlingerRequestsDisplay(false),
195 mMainThreadId(std::this_thread::get_id()),
196 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800198 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800199
200 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
201 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
202
203 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
204 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
205
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800206 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700209 useContextPriority = getBool< ISurfaceFlingerConfigs,
210 &ISurfaceFlingerConfigs::useContextPriority>(false);
211
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700212 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
213 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
214
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700215 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
216 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
217
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800218 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
219 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
220
Steven Thomas050b2c82017-03-06 11:45:16 -0800221 // Vr flinger is only enabled on Daydream ready devices.
222 useVrFlinger = getBool< ISurfaceFlingerConfigs,
223 &ISurfaceFlingerConfigs::useVrFlinger>(false);
224
Fabien Sanglard1971b632017-03-10 14:50:03 -0800225 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
226 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
227
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600228 hasWideColorDisplay =
229 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
230
Saurabh Shahf4174532017-07-13 10:45:07 -0700231 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233 // debugging stuff...
234 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700235
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700237 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239 property_get("debug.sf.showupdates", value, "0");
240 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700241
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700242 property_get("debug.sf.ddms", value, "0");
243 mDebugDDMS = atoi(value);
244 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700245 if (!startDdmConnection()) {
246 // start failed, and DDMS debugging not enabled
247 mDebugDDMS = 0;
248 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700249 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700250 ALOGI_IF(mDebugRegion, "showupdates enabled");
251 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700252
253 property_get("debug.sf.disable_backpressure", value, "0");
254 mPropagateBackpressure = !atoi(value);
255 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700256
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800257 property_get("debug.sf.enable_hwc_vds", value, "0");
258 mUseHwcVirtualDisplays = atoi(value);
259 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800260
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800261 property_get("ro.sf.disable_triple_buffer", value, "1");
262 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800263 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700264
Romain Guy11d63f42017-07-20 12:47:14 -0700265 // We should be reading 'persist.sys.sf.color_saturation' here
266 // but since /data may be encrypted, we need to wait until after vold
267 // comes online to attempt to read the property. The property is
268 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800269
270 if (useTrebleTestingOverride()) {
271 // Without the override SurfaceFlinger cannot connect to HIDL
272 // services that are not listed in the manifests. Considered
273 // deriving the setting from the set service name, but it
274 // would be brittle if the name that's not 'default' is used
275 // for production purposes later on.
276 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
277 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800278}
279
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800280void SurfaceFlinger::onFirstRef()
281{
282 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800283}
284
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800285SurfaceFlinger::~SurfaceFlinger()
286{
Mathias Agopiana4912602012-07-12 14:25:33 -0700287 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
288 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
289 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290}
291
Dan Stozac7014012014-02-14 15:03:43 -0800292void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800293{
294 // the window manager died on us. prepare its eulogy.
295
Andy McFadden13a082e2012-08-24 10:16:42 -0700296 // restore initial conditions (default device unblank, etc)
297 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800298
299 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700300 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800301}
302
Robert Carr1db73f62016-12-21 12:58:51 -0800303static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700304 status_t err = client->initCheck();
305 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800306 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307 }
Robert Carr1db73f62016-12-21 12:58:51 -0800308 return nullptr;
309}
310
311sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
312 return initClient(new Client(this));
313}
314
315sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
316 const sp<IGraphicBufferProducer>& gbp) {
317 if (authenticateSurfaceTexture(gbp) == false) {
318 return nullptr;
319 }
320 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
321 if (layer == nullptr) {
322 return nullptr;
323 }
324
325 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326}
327
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700328sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
329 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700330{
331 class DisplayToken : public BBinder {
332 sp<SurfaceFlinger> flinger;
333 virtual ~DisplayToken() {
334 // no more references, this display must be terminated
335 Mutex::Autolock _l(flinger->mStateLock);
336 flinger->mCurrentState.displays.removeItem(this);
337 flinger->setTransactionFlags(eDisplayTransactionNeeded);
338 }
339 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700340 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700341 : flinger(flinger) {
342 }
343 };
344
345 sp<BBinder> token = new DisplayToken(this);
346
347 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700348 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700349 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700350 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700351 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700352 return token;
353}
354
Jesse Hall6c913be2013-08-08 12:15:49 -0700355void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
356 Mutex::Autolock _l(mStateLock);
357
358 ssize_t idx = mCurrentState.displays.indexOfKey(display);
359 if (idx < 0) {
360 ALOGW("destroyDisplay: invalid display token");
361 return;
362 }
363
364 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
365 if (!info.isVirtualDisplay()) {
366 ALOGE("destroyDisplay called for non-virtual display");
367 return;
368 }
Irvelffc9efc2016-07-27 15:16:37 -0700369 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700370 mCurrentState.displays.removeItemsAt(idx);
371 setTransactionFlags(eDisplayTransactionNeeded);
372}
373
Jesse Hall692c7232012-11-08 15:41:56 -0800374void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800375 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800376 ALOGW_IF(mBuiltinDisplays[type],
377 "Overwriting display token for display type %d", type);
378 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800379 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700380 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800381 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700382 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800383}
384
Mathias Agopiane57f2922012-08-09 16:29:12 -0700385sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700386 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700387 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
388 return NULL;
389 }
Jesse Hall692c7232012-11-08 15:41:56 -0800390 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700391}
392
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800393void SurfaceFlinger::bootFinished()
394{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700395 if (mStartPropertySetThread->join() != NO_ERROR) {
396 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800397 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398 const nsecs_t now = systemTime();
399 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000400 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700401
402 // wait patiently for the window manager death
403 const String16 name("window");
404 sp<IBinder> window(defaultServiceManager()->getService(name));
405 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700406 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700407 }
408
Steven Thomas050b2c82017-03-06 11:45:16 -0800409 if (mVrFlinger) {
410 mVrFlinger->OnBootFinished();
411 }
412
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700413 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700414 // formerly we would just kill the process, but we now ask it to exit so it
415 // can choose where to stop the animation.
416 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700417
418 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
419 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
420 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700421
Thierry Strudel2924d012017-08-14 15:19:37 -0700422 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700423 readPersistentProperties();
424 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700425 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426}
427
Mathias Agopian3f844832013-08-07 21:24:32 -0700428void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700429 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700430 RenderEngine& engine;
431 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700432 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700433 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
434 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700435 }
436 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700437 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700438 return true;
439 }
440 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700441 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700442}
443
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700444class DispSyncSource : public VSyncSource, private DispSync::Callback {
445public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700446 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000447 const char* name) :
448 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700449 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700450 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000451 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
452 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700453 mDispSync(dispSync),
454 mCallbackMutex(),
455 mCallback(),
456 mVsyncMutex(),
457 mPhaseOffset(phaseOffset),
458 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700459
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700460 virtual ~DispSyncSource() {}
461
462 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700463 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700464 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000465 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700466 static_cast<DispSync::Callback*>(this));
467 if (err != NO_ERROR) {
468 ALOGE("error registering vsync callback: %s (%d)",
469 strerror(-err), err);
470 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700471 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700472 } else {
473 status_t err = mDispSync->removeEventListener(
474 static_cast<DispSync::Callback*>(this));
475 if (err != NO_ERROR) {
476 ALOGE("error unregistering vsync callback: %s (%d)",
477 strerror(-err), err);
478 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700479 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700481 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700482 }
483
484 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700485 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700486 mCallback = callback;
487 }
488
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700489 virtual void setPhaseOffset(nsecs_t phaseOffset) {
490 Mutex::Autolock lock(mVsyncMutex);
491
492 // Normalize phaseOffset to [0, period)
493 auto period = mDispSync->getPeriod();
494 phaseOffset %= period;
495 if (phaseOffset < 0) {
496 // If we're here, then phaseOffset is in (-period, 0). After this
497 // operation, it will be in (0, period)
498 phaseOffset += period;
499 }
500 mPhaseOffset = phaseOffset;
501
502 // If we're not enabled, we don't need to mess with the listeners
503 if (!mEnabled) {
504 return;
505 }
506
507 // Remove the listener with the old offset
508 status_t err = mDispSync->removeEventListener(
509 static_cast<DispSync::Callback*>(this));
510 if (err != NO_ERROR) {
511 ALOGE("error unregistering vsync callback: %s (%d)",
512 strerror(-err), err);
513 }
514
515 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000516 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700517 static_cast<DispSync::Callback*>(this));
518 if (err != NO_ERROR) {
519 ALOGE("error registering vsync callback: %s (%d)",
520 strerror(-err), err);
521 }
522 }
523
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700524private:
525 virtual void onDispSyncEvent(nsecs_t when) {
526 sp<VSyncSource::Callback> callback;
527 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700528 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700529 callback = mCallback;
530
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700531 if (mTraceVsync) {
532 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700533 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700534 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700535 }
536
537 if (callback != NULL) {
538 callback->onVSyncEvent(when);
539 }
540 }
541
Tim Murray4a4e4a22016-04-19 16:29:23 +0000542 const char* const mName;
543
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544 int mValue;
545
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700546 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700547 const String8 mVsyncOnLabel;
548 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700549
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700550 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700551
552 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700553 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700554
555 Mutex mVsyncMutex; // Protects the following
556 nsecs_t mPhaseOffset;
557 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700558};
559
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700560class InjectVSyncSource : public VSyncSource {
561public:
562 InjectVSyncSource() {}
563
564 virtual ~InjectVSyncSource() {}
565
566 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
567 std::lock_guard<std::mutex> lock(mCallbackMutex);
568 mCallback = callback;
569 }
570
571 virtual void onInjectSyncEvent(nsecs_t when) {
572 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700573 if (mCallback) {
574 mCallback->onVSyncEvent(when);
575 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700576 }
577
578 virtual void setVSyncEnabled(bool) {}
579 virtual void setPhaseOffset(nsecs_t) {}
580
581private:
582 std::mutex mCallbackMutex; // Protects the following
583 sp<VSyncSource::Callback> mCallback;
584};
585
Wei Wangf9b05ee2017-07-19 20:59:39 -0700586// Do not call property_set on main thread which will be blocked by init
587// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700589 ALOGI( "SurfaceFlinger's main thread ready to run. "
590 "Initializing graphics H/W...");
591
Thierry Strudel2924d012017-08-14 15:19:37 -0700592 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900593
Steven Thomasb02664d2017-07-26 18:48:28 -0700594 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800595
Steven Thomasb02664d2017-07-26 18:48:28 -0700596 // initialize EGL for the default display
597 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
598 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800599
Steven Thomasb02664d2017-07-26 18:48:28 -0700600 // start the EventThread
601 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
602 vsyncPhaseOffsetNs, true, "app");
603 mEventThread = new EventThread(vsyncSrc, *this, false);
604 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
605 sfVsyncPhaseOffsetNs, true, "sf");
606 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
607 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800608
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
610 struct sched_param param = {0};
611 param.sched_priority = 2;
612 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
613 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
614 }
615 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
616 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800617 }
618
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 // Get a RenderEngine for the given display / config (can't fail)
620 mRenderEngine = RenderEngine::create(mEGLDisplay,
621 HAL_PIXEL_FORMAT_RGBA_8888,
622 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 // retrieve the EGL context that was selected/created
625 mEGLContext = mRenderEngine->getEGLContext();
626
627 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
628 "couldn't create EGLContext");
629
630 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
631 "Starting with vr flinger active is not currently supported.");
632 mHwc.reset(new HWComposer(mHwcServiceName));
633 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800634
Steven Thomas050b2c82017-03-06 11:45:16 -0800635 if (useVrFlinger) {
636 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700637 // This callback is called from the vr flinger dispatch thread. We
638 // need to call signalTransaction(), which requires holding
639 // mStateLock when we're not on the main thread. Acquiring
640 // mStateLock from the vr flinger dispatch thread might trigger a
641 // deadlock in surface flinger (see b/66916578), so post a message
642 // to be handled on the main thread instead.
643 sp<LambdaMessage> message = new LambdaMessage([=]() {
644 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
645 mVrFlingerRequestsDisplay = requestDisplay;
646 signalTransaction();
647 });
648 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800649 };
650 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
651 vrFlingerRequestDisplayCallback);
652 if (!mVrFlinger) {
653 ALOGE("Failed to start vrflinger");
654 }
655 }
656
Jamie Gennisd1700752013-10-14 12:22:52 -0700657 mEventControlThread = new EventControlThread(this);
658 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
659
Mathias Agopian92a979a2012-08-02 18:32:23 -0700660 // initialize our drawing state
661 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700662
Andy McFadden13a082e2012-08-24 10:16:42 -0700663 // set initial conditions (e.g. unblank default device)
664 initializeDisplays();
665
Dan Stoza4e637772016-07-28 13:31:51 -0700666 mRenderEngine->primeCache();
667
Wei Wangf9b05ee2017-07-19 20:59:39 -0700668 // Inform native graphics APIs whether the present timestamp is supported:
669 if (getHwComposer().hasCapability(
670 HWC2::Capability::PresentFenceIsNotReliable)) {
671 mStartPropertySetThread = new StartPropertySetThread(false);
672 } else {
673 mStartPropertySetThread = new StartPropertySetThread(true);
674 }
675
676 if (mStartPropertySetThread->Start() != NO_ERROR) {
677 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800678 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800679
Dan Stoza9e56aa02015-11-02 13:00:03 -0800680 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700681}
682
Romain Guy11d63f42017-07-20 12:47:14 -0700683void SurfaceFlinger::readPersistentProperties() {
684 char value[PROPERTY_VALUE_MAX];
685
686 property_get("persist.sys.sf.color_saturation", value, "1.0");
687 mSaturation = atof(value);
688 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100689
690 property_get("persist.sys.sf.native_mode", value, "0");
691 mForceNativeColorMode = atoi(value) == 1;
692 if (mForceNativeColorMode) {
693 ALOGV("Forcing native color mode");
694 }
Romain Guy11d63f42017-07-20 12:47:14 -0700695}
696
Mathias Agopiana67e4182012-06-19 17:26:12 -0700697void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800698 // Start boot animation service by setting a property mailbox
699 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700700 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800701 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700702 if (mStartPropertySetThread->join() != NO_ERROR) {
703 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800704 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700705}
706
Mathias Agopian875d8e12013-06-07 15:35:48 -0700707size_t SurfaceFlinger::getMaxTextureSize() const {
708 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700709}
710
Mathias Agopian875d8e12013-06-07 15:35:48 -0700711size_t SurfaceFlinger::getMaxViewportDims() const {
712 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700713}
714
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800715// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800716
Jamie Gennis582270d2011-08-17 18:19:00 -0700717bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800718 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800719 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800720 return authenticateSurfaceTextureLocked(bufferProducer);
721}
722
723bool SurfaceFlinger::authenticateSurfaceTextureLocked(
724 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800725 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700726 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800727}
728
Brian Anderson6b376712017-04-04 10:51:39 -0700729status_t SurfaceFlinger::getSupportedFrameTimestamps(
730 std::vector<FrameEvent>* outSupported) const {
731 *outSupported = {
732 FrameEvent::REQUESTED_PRESENT,
733 FrameEvent::ACQUIRE,
734 FrameEvent::LATCH,
735 FrameEvent::FIRST_REFRESH_START,
736 FrameEvent::LAST_REFRESH_START,
737 FrameEvent::GPU_COMPOSITION_DONE,
738 FrameEvent::DEQUEUE_READY,
739 FrameEvent::RELEASE,
740 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700741 ConditionalLock _l(mStateLock,
742 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700743 if (!getHwComposer().hasCapability(
744 HWC2::Capability::PresentFenceIsNotReliable)) {
745 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
746 }
747 return NO_ERROR;
748}
749
Dan Stoza7f7da322014-05-02 15:26:25 -0700750status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
751 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700752 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700753 return BAD_VALUE;
754 }
755
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500756 if (!display.get())
757 return NAME_NOT_FOUND;
758
Jesse Hall692c7232012-11-08 15:41:56 -0800759 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700760 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800761 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700762 type = i;
763 break;
764 }
765 }
766
767 if (type < 0) {
768 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700769 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700770
Mathias Agopian8b736f12012-08-13 17:54:26 -0700771 // TODO: Not sure if display density should handled by SF any longer
772 class Density {
773 static int getDensityFromProperty(char const* propName) {
774 char property[PROPERTY_VALUE_MAX];
775 int density = 0;
776 if (property_get(propName, property, NULL) > 0) {
777 density = atoi(property);
778 }
779 return density;
780 }
781 public:
782 static int getEmuDensity() {
783 return getDensityFromProperty("qemu.sf.lcd_density"); }
784 static int getBuildDensity() {
785 return getDensityFromProperty("ro.sf.lcd_density"); }
786 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700787
Dan Stoza7f7da322014-05-02 15:26:25 -0700788 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700789
Steven Thomas6d8110b2017-08-31 18:24:21 -0700790 ConditionalLock _l(mStateLock,
791 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800792 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700793 DisplayInfo info = DisplayInfo();
794
Dan Stoza9e56aa02015-11-02 13:00:03 -0800795 float xdpi = hwConfig->getDpiX();
796 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700797
798 if (type == DisplayDevice::DISPLAY_PRIMARY) {
799 // The density of the device is provided by a build property
800 float density = Density::getBuildDensity() / 160.0f;
801 if (density == 0) {
802 // the build doesn't provide a density -- this is wrong!
803 // use xdpi instead
804 ALOGE("ro.sf.lcd_density must be defined as a build property");
805 density = xdpi / 160.0f;
806 }
807 if (Density::getEmuDensity()) {
808 // if "qemu.sf.lcd_density" is specified, it overrides everything
809 xdpi = ydpi = density = Density::getEmuDensity();
810 density /= 160.0f;
811 }
812 info.density = density;
813
814 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700815 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000816 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700817 } else {
818 // TODO: where should this value come from?
819 static const int TV_DENSITY = 213;
820 info.density = TV_DENSITY / 160.0f;
821 info.orientation = 0;
822 }
823
Dan Stoza9e56aa02015-11-02 13:00:03 -0800824 info.w = hwConfig->getWidth();
825 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700826 info.xdpi = xdpi;
827 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900829 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830
Andy McFadden91b2ca82014-06-13 14:04:23 -0700831 // This is how far in advance a buffer must be queued for
832 // presentation at a given time. If you want a buffer to appear
833 // on the screen at time N, you must submit the buffer before
834 // (N - presentationDeadline).
835 //
836 // Normally it's one full refresh period (to give SF a chance to
837 // latch the buffer), but this can be reduced by configuring a
838 // DispSync offset. Any additional delays introduced by the hardware
839 // composer or panel must be accounted for here.
840 //
841 // We add an additional 1ms to allow for processing time and
842 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800843 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800844 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700845
846 // All non-virtual displays are currently considered secure.
847 info.secure = true;
848
Michael Wright28f24d02016-07-12 13:30:53 -0700849 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850 }
851
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 return NO_ERROR;
853}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700854
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800855status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700856 DisplayStatInfo* stats) {
857 if (stats == NULL) {
858 return BAD_VALUE;
859 }
860
861 // FIXME for now we always return stats for the primary display
862 memset(stats, 0, sizeof(*stats));
863 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
864 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
865 return NO_ERROR;
866}
867
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700868int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800869 if (display == NULL) {
870 ALOGE("%s : display is NULL", __func__);
871 return BAD_VALUE;
872 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700873
874 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700875 if (device != NULL) {
876 return device->getActiveConfig();
877 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700878
Dan Stoza24a42e92015-03-09 10:04:11 -0700879 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700880}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700881
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700882void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
883 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
884 this);
885 int32_t type = hw->getDisplayType();
886 int currentMode = hw->getActiveConfig();
887
888 if (mode == currentMode) {
889 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
890 return;
891 }
892
893 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
894 ALOGW("Trying to set config for virtual display");
895 return;
896 }
897
898 hw->setActiveConfig(mode);
899 getHwComposer().setActiveConfig(type, mode);
900}
901
902status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
903 class MessageSetActiveConfig: public MessageBase {
904 SurfaceFlinger& mFlinger;
905 sp<IBinder> mDisplay;
906 int mMode;
907 public:
908 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
909 int mode) :
910 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
911 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700912 Vector<DisplayInfo> configs;
913 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700914 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700915 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700916 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700917 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700918 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700919 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
920 if (hw == NULL) {
921 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700922 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700923 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
924 ALOGW("Attempt to set active config = %d for virtual display",
925 mMode);
926 } else {
927 mFlinger.setActiveConfigInternal(hw, mMode);
928 }
929 return true;
930 }
931 };
932 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
933 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700934 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700935}
Michael Wright28f24d02016-07-12 13:30:53 -0700936status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
937 Vector<android_color_mode_t>* outColorModes) {
938 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
939 return BAD_VALUE;
940 }
941
942 if (!display.get()) {
943 return NAME_NOT_FOUND;
944 }
945
946 int32_t type = NAME_NOT_FOUND;
947 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
948 if (display == mBuiltinDisplays[i]) {
949 type = i;
950 break;
951 }
952 }
953
954 if (type < 0) {
955 return type;
956 }
957
Steven Thomas6d8110b2017-08-31 18:24:21 -0700958 std::vector<android_color_mode_t> modes;
959 {
960 ConditionalLock _l(mStateLock,
961 std::this_thread::get_id() != mMainThreadId);
962 modes = getHwComposer().getColorModes(type);
963 }
Michael Wright28f24d02016-07-12 13:30:53 -0700964 outColorModes->clear();
965 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
966
967 return NO_ERROR;
968}
969
970android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700971 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700972 if (device != nullptr) {
973 return device->getActiveColorMode();
974 }
975 return static_cast<android_color_mode_t>(BAD_VALUE);
976}
977
978void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
979 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700980 int32_t type = hw->getDisplayType();
981 android_color_mode_t currentMode = hw->getActiveColorMode();
982
983 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700984 return;
985 }
986
987 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
988 ALOGW("Trying to set config for virtual display");
989 return;
990 }
991
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600992 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
993 hw->getDisplayType());
994
Michael Wright28f24d02016-07-12 13:30:53 -0700995 hw->setActiveColorMode(mode);
996 getHwComposer().setActiveColorMode(type, mode);
997}
998
999
1000status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
1001 android_color_mode_t colorMode) {
1002 class MessageSetActiveColorMode: public MessageBase {
1003 SurfaceFlinger& mFlinger;
1004 sp<IBinder> mDisplay;
1005 android_color_mode_t mMode;
1006 public:
1007 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1008 android_color_mode_t mode) :
1009 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1010 virtual bool handler() {
1011 Vector<android_color_mode_t> modes;
1012 mFlinger.getDisplayColorModes(mDisplay, &modes);
1013 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1014 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001015 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1016 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001017 return true;
1018 }
1019 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1020 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001021 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1022 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001023 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001024 ALOGW("Attempt to set active color mode %s %d for virtual display",
1025 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001026 } else {
1027 mFlinger.setActiveColorModeInternal(hw, mMode);
1028 }
1029 return true;
1030 }
1031 };
1032 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1033 postMessageSync(msg);
1034 return NO_ERROR;
1035}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001036
Svetoslavd85084b2014-03-20 10:28:31 -07001037status_t SurfaceFlinger::clearAnimationFrameStats() {
1038 Mutex::Autolock _l(mStateLock);
1039 mAnimFrameTracker.clearStats();
1040 return NO_ERROR;
1041}
1042
1043status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1044 Mutex::Autolock _l(mStateLock);
1045 mAnimFrameTracker.getStats(outStats);
1046 return NO_ERROR;
1047}
1048
Dan Stozac4f471e2016-03-24 09:31:08 -07001049status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1050 HdrCapabilities* outCapabilities) const {
1051 Mutex::Autolock _l(mStateLock);
1052
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001053 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001054 if (displayDevice == nullptr) {
1055 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1056 return BAD_VALUE;
1057 }
1058
1059 std::unique_ptr<HdrCapabilities> capabilities =
1060 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1061 if (capabilities) {
1062 std::swap(*outCapabilities, *capabilities);
1063 } else {
1064 return BAD_VALUE;
1065 }
1066
1067 return NO_ERROR;
1068}
1069
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001070status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001071 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1072 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001073
Chia-I Wu90f669f2017-10-05 14:24:41 -07001074 if (mInjectVSyncs == enable) {
1075 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001076 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001077
1078 if (enable) {
1079 ALOGV("VSync Injections enabled");
1080 if (mVSyncInjector.get() == nullptr) {
1081 mVSyncInjector = new InjectVSyncSource();
1082 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1083 }
1084 mEventQueue.setEventThread(mInjectorEventThread);
1085 } else {
1086 ALOGV("VSync Injections disabled");
1087 mEventQueue.setEventThread(mSFEventThread);
1088 }
1089
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001090 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001091 });
1092 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001093 return NO_ERROR;
1094}
1095
1096status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001097 Mutex::Autolock _l(mStateLock);
1098
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001099 if (!mInjectVSyncs) {
1100 ALOGE("VSync Injections not enabled");
1101 return BAD_VALUE;
1102 }
1103 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1104 ALOGV("Injecting VSync inside SurfaceFlinger");
1105 mVSyncInjector->onInjectSyncEvent(when);
1106 }
1107 return NO_ERROR;
1108}
1109
Kalle Raitaa099a242017-01-11 11:17:29 -08001110status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1111 IPCThreadState* ipc = IPCThreadState::self();
1112 const int pid = ipc->getCallingPid();
1113 const int uid = ipc->getCallingUid();
1114 if ((uid != AID_SHELL) &&
1115 !PermissionCache::checkPermission(sDump, pid, uid)) {
1116 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1117 return PERMISSION_DENIED;
1118 }
1119
1120 // Try to acquire a lock for 1s, fail gracefully
1121 const status_t err = mStateLock.timedLock(s2ns(1));
1122 const bool locked = (err == NO_ERROR);
1123 if (!locked) {
1124 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1125 return TIMED_OUT;
1126 }
1127
1128 outLayers->clear();
1129 mCurrentState.traverseInZOrder([&](Layer* layer) {
1130 outLayers->push_back(layer->getLayerDebugInfo());
1131 });
1132
1133 mStateLock.unlock();
1134 return NO_ERROR;
1135}
1136
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001137// ----------------------------------------------------------------------------
1138
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001139sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1140 ISurfaceComposer::VsyncSource vsyncSource) {
1141 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1142 return mSFEventThread->createEventConnection();
1143 } else {
1144 return mEventThread->createEventConnection();
1145 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001146}
1147
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001148// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001149
1150void SurfaceFlinger::waitForEvent() {
1151 mEventQueue.waitMessage();
1152}
1153
1154void SurfaceFlinger::signalTransaction() {
1155 mEventQueue.invalidate();
1156}
1157
1158void SurfaceFlinger::signalLayerUpdate() {
1159 mEventQueue.invalidate();
1160}
1161
1162void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001163 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001164 mEventQueue.refresh();
1165}
1166
1167status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001168 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001169 return mEventQueue.postMessage(msg, reltime);
1170}
1171
1172status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001173 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001174 status_t res = mEventQueue.postMessage(msg, reltime);
1175 if (res == NO_ERROR) {
1176 msg->wait();
1177 }
1178 return res;
1179}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001180
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001181void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001182 do {
1183 waitForEvent();
1184 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001185}
1186
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187void SurfaceFlinger::enableHardwareVsync() {
1188 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001189 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001190 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001191 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1192 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001193 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001194 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195}
1196
Jesse Hall948fe0c2013-10-14 12:56:09 -07001197void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001198 Mutex::Autolock _l(mHWVsyncLock);
1199
Jesse Hall948fe0c2013-10-14 12:56:09 -07001200 if (makeAvailable) {
1201 mHWVsyncAvailable = true;
1202 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001203 // Hardware vsync is not currently available, so abort the resync
1204 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001205 return;
1206 }
1207
Dan Stoza9e56aa02015-11-02 13:00:03 -08001208 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1209 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001210
1211 mPrimaryDispSync.reset();
1212 mPrimaryDispSync.setPeriod(period);
1213
1214 if (!mPrimaryHWVsyncEnabled) {
1215 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001216 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1217 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 mPrimaryHWVsyncEnabled = true;
1219 }
1220}
1221
Jesse Hall948fe0c2013-10-14 12:56:09 -07001222void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223 Mutex::Autolock _l(mHWVsyncLock);
1224 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001225 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1226 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001227 mPrimaryDispSync.endResync();
1228 mPrimaryHWVsyncEnabled = false;
1229 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001230 if (makeUnavailable) {
1231 mHWVsyncAvailable = false;
1232 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233}
1234
Tim Murray4a4e4a22016-04-19 16:29:23 +00001235void SurfaceFlinger::resyncWithRateLimit() {
1236 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001237
1238 // No explicit locking is needed here since EventThread holds a lock while calling this method
1239 static nsecs_t sLastResyncAttempted = 0;
1240 const nsecs_t now = systemTime();
1241 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001242 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001243 }
Dan Stoza57164302017-05-08 14:03:54 -07001244 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001245}
1246
Steven Thomasb02664d2017-07-26 18:48:28 -07001247void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1248 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001249 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001250 // Ignore any vsyncs from a previous hardware composer.
1251 if (sequenceId != mComposerSequenceId) {
1252 return;
1253 }
1254
1255 int32_t type;
1256 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001257 return;
1258 }
1259
Jamie Gennisd1700752013-10-14 12:22:52 -07001260 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261
Jamie Gennisd1700752013-10-14 12:22:52 -07001262 { // Scope for the lock
1263 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001264 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001265 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001266 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001267 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001268
1269 if (needsHwVsync) {
1270 enableHardwareVsync();
1271 } else {
1272 disableHardwareVsync(false);
1273 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001274}
1275
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001276void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001277 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001278 *compositorTiming = mCompositorTiming;
1279}
1280
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001281void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001282 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001283 wp<IBinder> token = mBuiltinDisplays[type];
1284
1285 // All non-virtual displays are currently considered secure.
1286 const bool isSecure = true;
1287
1288 sp<IGraphicBufferProducer> producer;
1289 sp<IGraphicBufferConsumer> consumer;
1290 BufferQueue::createBufferQueue(&producer, &consumer);
1291
1292 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1293
1294 bool hasWideColorModes = false;
1295 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1296 for (android_color_mode_t colorMode : modes) {
1297 switch (colorMode) {
1298 case HAL_COLOR_MODE_DISPLAY_P3:
1299 case HAL_COLOR_MODE_ADOBE_RGB:
1300 case HAL_COLOR_MODE_DCI_P3:
1301 hasWideColorModes = true;
1302 break;
1303 default:
1304 break;
1305 }
1306 }
Romain Guy54f154a2017-10-24 21:40:32 +01001307 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001308 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1309 token, fbs, producer, mRenderEngine->getEGLConfig(),
Romain Guy54f154a2017-10-24 21:40:32 +01001310 useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001311 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001312 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001313 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001314 defaultColorMode = HAL_COLOR_MODE_SRGB;
1315 }
1316 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001317 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001318
1319 // Add the primary display token to mDrawingState so we don't try to
1320 // recreate the DisplayDevice for the primary display.
1321 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1322
1323 // make the GLContext current so that we can create textures when creating
1324 // Layers (which may happens before we render something)
1325 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001326}
1327
Steven Thomasb02664d2017-07-26 18:48:28 -07001328void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1329 hwc2_display_t display, HWC2::Connection connection,
1330 bool primaryDisplay) {
1331 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1332 sequenceId, display,
1333 connection == HWC2::Connection::Connected ?
1334 "connected" : "disconnected",
1335 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001336
Steven Thomasb02664d2017-07-26 18:48:28 -07001337 // Only lock if we're not on the main thread. This function is normally
1338 // called on a hwbinder thread, but for the primary display it's called on
1339 // the main thread with the state lock already held, so don't attempt to
1340 // acquire it here.
1341 ConditionalLock lock(mStateLock,
1342 std::this_thread::get_id() != mMainThreadId);
1343
1344 if (primaryDisplay) {
1345 mHwc->onHotplug(display, connection);
1346 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1347 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001348 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001349 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001350 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001351 if (sequenceId != mComposerSequenceId) {
1352 return;
1353 }
1354 if (mHwc->isUsingVrComposer()) {
1355 ALOGE("External displays are not supported by the vr hardware composer.");
1356 return;
1357 }
1358 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001359 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001361 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001362 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001363 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1364 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001365 }
1366 setTransactionFlags(eDisplayTransactionNeeded);
1367
Andy McFadden9e9689c2012-10-10 18:17:51 -07001368 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001369 }
Mathias Agopian86303202012-07-24 22:46:10 -07001370}
1371
Steven Thomasb02664d2017-07-26 18:48:28 -07001372void SurfaceFlinger::onRefreshReceived(int sequenceId,
1373 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001374 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 if (sequenceId != mComposerSequenceId) {
1376 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001377 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001378 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001379}
1380
Dan Stoza9e56aa02015-11-02 13:00:03 -08001381void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001382 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001384 getHwComposer().setVsyncEnabled(disp,
1385 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001386}
1387
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001388// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001389void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001390 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001391 // Clear the drawing state so that the logic inside of
1392 // handleTransactionLocked will fire. It will determine the delta between
1393 // mCurrentState and mDrawingState and re-apply all changes when we make the
1394 // transition.
1395 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001397 mDisplays.clear();
1398}
1399
Steven Thomas050b2c82017-03-06 11:45:16 -08001400void SurfaceFlinger::updateVrFlinger() {
1401 if (!mVrFlinger)
1402 return;
1403 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1404 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001405 return;
1406 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001407
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1409 ALOGE("Vr flinger is only supported for remote hardware composer"
1410 " service connections. Ignoring request to transition to vr"
1411 " flinger.");
1412 mVrFlingerRequestsDisplay = false;
1413 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001414 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001415
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001416 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 int currentDisplayPowerMode = getDisplayDeviceLocked(
1419 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001420
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001422 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001424
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 resetDisplayState();
1426 mHwc.reset(); // Delete the current instance before creating the new one
1427 mHwc.reset(new HWComposer(
1428 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1429 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1432 "Switched to non-remote hardware composer");
1433
1434 if (vrFlingerRequestsDisplay) {
1435 mVrFlinger->GrantDisplayOwnership();
1436 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001437 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001438 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001439
1440 mVisibleRegionsDirty = true;
1441 invalidateHwcGeometry();
1442
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001443 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1445 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1446 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001447
Steven Thomasb02664d2017-07-26 18:48:28 -07001448 // Reset the timing values to account for the period of the swapped in HWC
1449 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1450 const nsecs_t period = activeConfig->getVsyncPeriod();
1451 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001452
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 // Use phase of 0 since phase is not known.
1454 // Use latency of 0, which will snap to the ideal latency.
1455 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001456
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001457 android_atomic_or(1, &mRepaintEverything);
1458 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001459}
1460
Mathias Agopian4fec8732012-06-29 14:12:52 -07001461void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001462 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001463 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001464 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001465 bool frameMissed = !mHadClientComposition &&
1466 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001467 (mPreviousPresentFence->getSignalTime() ==
1468 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001469 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001470 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001471 signalLayerUpdate();
1472 break;
1473 }
1474
Steven Thomas050b2c82017-03-06 11:45:16 -08001475 // Now that we're going to make it to the handleMessageTransaction()
1476 // call below it's safe to call updateVrFlinger(), which will
1477 // potentially trigger a display handoff.
1478 updateVrFlinger();
1479
Dan Stoza6b9454d2014-11-07 16:00:59 -08001480 bool refreshNeeded = handleMessageTransaction();
1481 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001482 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001483 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001484 // Signal a refresh if a transaction modified the window state,
1485 // a new buffer was latched, or if HWC has requested a full
1486 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001487 signalRefresh();
1488 }
1489 break;
1490 }
1491 case MessageQueue::REFRESH: {
1492 handleMessageRefresh();
1493 break;
1494 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001495 }
1496}
1497
Dan Stoza6b9454d2014-11-07 16:00:59 -08001498bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001499 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001500 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001501 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001502 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001503 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001505}
1506
Dan Stoza6b9454d2014-11-07 16:00:59 -08001507bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001508 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001509 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001510}
1511
1512void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001514
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001515 mRefreshPending = false;
1516
Pablo Ceballos40845df2016-01-25 17:41:15 -08001517 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001518
Brian Andersond6927fb2016-07-23 23:37:30 -07001519 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001520 rebuildLayerStacks();
1521 setUpHWComposer();
1522 doDebugFlashRegions();
1523 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001524 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001525
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001526 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001527
1528 mHadClientComposition = false;
1529 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1530 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1531 mHadClientComposition = mHadClientComposition ||
1532 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1533 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001534
Dan Stoza9e56aa02015-11-02 13:00:03 -08001535 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001536}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001537
Mathias Agopiancd60f992012-08-16 16:28:27 -07001538void SurfaceFlinger::doDebugFlashRegions()
1539{
1540 // is debugging enabled
1541 if (CC_LIKELY(!mDebugRegion))
1542 return;
1543
1544 const bool repaintEverything = mRepaintEverything;
1545 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1546 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001547 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001548 // transform the dirty region into this screen's coordinate space
1549 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1550 if (!dirtyRegion.isEmpty()) {
1551 // redraw the whole screen
1552 doComposeSurfaces(hw, Region(hw->bounds()));
1553
1554 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001556 RenderEngine& engine(getRenderEngine());
1557 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1558
Mathias Agopianda27af92012-09-13 18:17:13 -07001559 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560 }
1561 }
1562 }
1563
1564 postFramebuffer();
1565
1566 if (mDebugRegion > 1) {
1567 usleep(mDebugRegion * 1000);
1568 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001569
Dan Stoza9e56aa02015-11-02 13:00:03 -08001570 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001571 auto& displayDevice = mDisplays[displayId];
1572 if (!displayDevice->isDisplayOn()) {
1573 continue;
1574 }
1575
1576 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001577 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1578 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001579 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001580}
1581
Brian Andersond6927fb2016-07-23 23:37:30 -07001582void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001583{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001584 ATRACE_CALL();
1585 ALOGV("preComposition");
1586
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001588 mDrawingState.traverseInZOrder([&](Layer* layer) {
1589 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001590 needExtraInvalidate = true;
1591 }
Robert Carr2047fae2016-11-28 14:09:09 -08001592 });
1593
Mathias Agopiancd60f992012-08-16 16:28:27 -07001594 if (needExtraInvalidate) {
1595 signalLayerUpdate();
1596 }
1597}
1598
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001599void SurfaceFlinger::updateCompositorTiming(
1600 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1601 std::shared_ptr<FenceTime>& presentFenceTime) {
1602 // Update queue of past composite+present times and determine the
1603 // most recently known composite to present latency.
1604 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1605 nsecs_t compositeToPresentLatency = -1;
1606 while (!mCompositePresentTimes.empty()) {
1607 CompositePresentTime& cpt = mCompositePresentTimes.front();
1608 // Cached values should have been updated before calling this method,
1609 // which helps avoid duplicate syscalls.
1610 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1611 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1612 break;
1613 }
1614 compositeToPresentLatency = displayTime - cpt.composite;
1615 mCompositePresentTimes.pop();
1616 }
1617
1618 // Don't let mCompositePresentTimes grow unbounded, just in case.
1619 while (mCompositePresentTimes.size() > 16) {
1620 mCompositePresentTimes.pop();
1621 }
1622
Brian Andersond0010582017-03-07 13:20:31 -08001623 setCompositorTimingSnapped(
1624 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1625}
1626
1627void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1628 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001629 // Integer division and modulo round toward 0 not -inf, so we need to
1630 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001631 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001632 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1633 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1634
Brian Andersond0010582017-03-07 13:20:31 -08001635 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1636 if (idealLatency <= 0) {
1637 idealLatency = vsyncInterval;
1638 }
1639
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001640 // Snap the latency to a value that removes scheduling jitter from the
1641 // composition and present times, which often have >1ms of jitter.
1642 // Reducing jitter is important if an app attempts to extrapolate
1643 // something (such as user input) to an accurate diasplay time.
1644 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1645 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001646 nsecs_t bias = vsyncInterval / 2;
1647 int64_t extraVsyncs =
1648 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1649 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1650 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001651
Brian Andersond0010582017-03-07 13:20:31 -08001652 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1654 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001655 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656}
1657
1658void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001659{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001660 ATRACE_CALL();
1661 ALOGV("postComposition");
1662
Brian Anderson3546a3f2016-07-14 11:51:14 -07001663 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001664 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001665 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001666 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001667 }
1668
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001669 // |mStateLock| not needed as we are on the main thread
1670 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001671
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001672 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001673 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1674 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1675 glCompositionDoneFenceTime =
1676 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1677 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1678 } else {
1679 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1680 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001681
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001682 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001683 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1684 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1685 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001686
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001687 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1688 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1689
1690 // We use the refreshStartTime which might be sampled a little later than
1691 // when we started doing work for this frame, but that should be okay
1692 // since updateCompositorTiming has snapping logic.
1693 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001694 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001695 CompositorTiming compositorTiming;
1696 {
1697 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1698 compositorTiming = mCompositorTiming;
1699 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001700
Robert Carr2047fae2016-11-28 14:09:09 -08001701 mDrawingState.traverseInZOrder([&](Layer* layer) {
1702 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001703 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001704 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001705 recordBufferingStats(layer->getName().string(),
1706 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001707 }
Robert Carr2047fae2016-11-28 14:09:09 -08001708 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001709
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001710 if (presentFenceTime->isValid()) {
1711 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001712 enableHardwareVsync();
1713 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001714 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001715 }
1716 }
1717
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001718 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001719 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001720 enableHardwareVsync();
1721 }
1722 }
1723
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001724 if (mAnimCompositionPending) {
1725 mAnimCompositionPending = false;
1726
Brian Anderson4e606e32017-03-16 15:34:57 -07001727 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001728 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001729 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001730 } else {
1731 // The HWC doesn't support present fences, so use the refresh
1732 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001733 nsecs_t presentTime =
1734 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001735 mAnimFrameTracker.setActualPresentTime(presentTime);
1736 }
1737 mAnimFrameTracker.advanceFrame();
1738 }
Dan Stozab90cf072015-03-05 11:05:59 -08001739
1740 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1741 return;
1742 }
1743
1744 nsecs_t currentTime = systemTime();
1745 if (mHasPoweredOff) {
1746 mHasPoweredOff = false;
1747 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001748 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001749 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001750 if (numPeriods < NUM_BUCKETS - 1) {
1751 mFrameBuckets[numPeriods] += elapsedTime;
1752 } else {
1753 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1754 }
1755 mTotalTime += elapsedTime;
1756 }
1757 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001758}
1759
1760void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001761 ATRACE_CALL();
1762 ALOGV("rebuildLayerStacks");
1763
Mathias Agopiancd60f992012-08-16 16:28:27 -07001764 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001765 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001766 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001767 mVisibleRegionsDirty = false;
1768 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001769
Jeff Sharkey76488112017-02-27 14:15:18 -07001770 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1771 Region opaqueRegion;
1772 Region dirtyRegion;
1773 Vector<sp<Layer>> layersSortedByZ;
1774 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1775 const Transform& tr(displayDevice->getTransform());
1776 const Rect bounds(displayDevice->getBounds());
1777 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001778 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001779
Jeff Sharkey76488112017-02-27 14:15:18 -07001780 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001781 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1782 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001783 Region drawRegion(tr.transform(
1784 layer->visibleNonTransparentRegion));
1785 drawRegion.andSelf(bounds);
1786 if (!drawRegion.isEmpty()) {
1787 layersSortedByZ.add(layer);
1788 } else {
1789 // Clear out the HWC layer if this layer was
1790 // previously visible, but no longer is
Steven Thomasb02664d2017-07-26 18:48:28 -07001791 layer->destroyHwcLayer(
1792 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001793 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001794 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001795 // WM changes displayDevice->layerStack upon sleep/awake.
1796 // Here we make sure we delete the HWC layers even if
1797 // WM changed their layer stack.
Steven Thomasb02664d2017-07-26 18:48:28 -07001798 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001799 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001800 });
1801 }
1802 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1803 displayDevice->undefinedRegion.set(bounds);
1804 displayDevice->undefinedRegion.subtractSelf(
1805 tr.transform(opaqueRegion));
1806 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001807 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001808 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001809}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001810
Romain Guy0147a172017-06-01 13:53:56 -07001811mat4 SurfaceFlinger::computeSaturationMatrix() const {
1812 if (mSaturation == 1.0f) {
1813 return mat4();
1814 }
1815
1816 // Rec.709 luma coefficients
1817 float3 luminance{0.213f, 0.715f, 0.072f};
1818 luminance *= 1.0f - mSaturation;
1819 return mat4(
1820 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1821 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1822 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1823 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1824 );
1825}
1826
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001827// pickColorMode translates a given dataspace into the best available color mode.
1828// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001829android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001830 if (mForceNativeColorMode) {
1831 return HAL_COLOR_MODE_NATIVE;
1832 }
1833
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001834 switch (dataSpace) {
1835 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1836 // system expects.
1837 case HAL_DATASPACE_UNKNOWN:
1838 case HAL_DATASPACE_SRGB:
1839 case HAL_DATASPACE_V0_SRGB:
1840 return HAL_COLOR_MODE_SRGB;
1841 break;
1842
1843 case HAL_DATASPACE_DISPLAY_P3:
1844 return HAL_COLOR_MODE_DISPLAY_P3;
1845 break;
1846
1847 default:
1848 // TODO (courtneygo): Do we want to assert an error here?
1849 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1850 dataSpace);
1851 return HAL_COLOR_MODE_SRGB;
1852 break;
1853 }
1854}
1855
Romain Guy0147a172017-06-01 13:53:56 -07001856android_dataspace SurfaceFlinger::bestTargetDataSpace(
1857 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001858 // Only support sRGB and Display-P3 right now.
1859 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1860 return HAL_DATASPACE_DISPLAY_P3;
1861 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001862 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1863 return HAL_DATASPACE_DISPLAY_P3;
1864 }
1865 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1866 return HAL_DATASPACE_DISPLAY_P3;
1867 }
1868
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001869 return HAL_DATASPACE_V0_SRGB;
1870}
1871
Mathias Agopiancd60f992012-08-16 16:28:27 -07001872void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001873 ATRACE_CALL();
1874 ALOGV("setUpHWComposer");
1875
Jesse Hall028dc8f2013-08-20 16:35:32 -07001876 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001877 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1878 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1879 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1880
1881 // If nothing has changed (!dirty), don't recompose.
1882 // If something changed, but we don't currently have any visible layers,
1883 // and didn't when we last did a composition, then skip it this time.
1884 // The second rule does two things:
1885 // - When all layers are removed from a display, we'll emit one black
1886 // frame, then nothing more until we get new layers.
1887 // - When a display is created with a private layer stack, we won't
1888 // emit any black frames until a layer is added to the layer stack.
1889 bool mustRecompose = dirty && !(empty && wasEmpty);
1890
1891 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1892 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1893 mustRecompose ? "doing" : "skipping",
1894 dirty ? "+" : "-",
1895 empty ? "+" : "-",
1896 wasEmpty ? "+" : "-");
1897
Dan Stoza71433162014-02-04 16:22:36 -08001898 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001899
1900 if (mustRecompose) {
1901 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1902 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001903 }
1904
Dan Stoza9e56aa02015-11-02 13:00:03 -08001905 // build the h/w work list
1906 if (CC_UNLIKELY(mGeometryInvalid)) {
1907 mGeometryInvalid = false;
1908 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1909 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1910 const auto hwcId = displayDevice->getHwcDisplayId();
1911 if (hwcId >= 0) {
1912 const Vector<sp<Layer>>& currentLayers(
1913 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001914 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001915 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001916 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001917 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001918 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001919 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001920 }
1921 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001922
Robert Carrae060832016-11-28 10:51:00 -08001923 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001924 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001926 }
1927 }
1928 }
1929 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001930 }
Riley Andrews03414a12014-07-01 14:22:59 -07001931
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001932
Romain Guy0147a172017-06-01 13:53:56 -07001933 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001934
Dan Stoza9e56aa02015-11-02 13:00:03 -08001935 // Set the per-frame data
1936 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1937 auto& displayDevice = mDisplays[displayId];
1938 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001939
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 if (hwcId < 0) {
1941 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001942 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001943 if (colorMatrix != mPreviousColorMatrix) {
1944 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1945 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1946 "display %zd: %d", displayId, result);
1947 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001948 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1949 layer->setPerFrameData(displayDevice);
1950 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001951
1952 if (hasWideColorDisplay) {
1953 android_color_mode newColorMode;
1954 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1955
1956 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1957 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1958 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1959 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1960 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1961 }
1962 newColorMode = pickColorMode(newDataSpace);
1963
Thierry Strudel2924d012017-08-14 15:19:37 -07001964 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001965 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001966 }
1967
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001968 mPreviousColorMatrix = colorMatrix;
1969
Dan Stoza9e56aa02015-11-02 13:00:03 -08001970 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001971 auto& displayDevice = mDisplays[displayId];
1972 if (!displayDevice->isDisplayOn()) {
1973 continue;
1974 }
1975
1976 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001977 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1978 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001979 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001980}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001981
Mathias Agopiancd60f992012-08-16 16:28:27 -07001982void SurfaceFlinger::doComposition() {
1983 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 ALOGV("doComposition");
1985
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001986 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001987 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001988 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001989 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001990 // transform the dirty region into this screen's coordinate space
1991 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001992
1993 // repaint the framebuffer (if needed)
1994 doDisplayComposition(hw, dirtyRegion);
1995
Mathias Agopiancd60f992012-08-16 16:28:27 -07001996 hw->dirtyRegion.clear();
1997 hw->flip(hw->swapRegion);
1998 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001999 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002000 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002001 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002002}
2003
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002004void SurfaceFlinger::postFramebuffer()
2005{
Mathias Agopian841cde52012-03-01 15:44:37 -08002006 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002007 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002008
Mathias Agopiana44b0412011-10-16 18:46:35 -07002009 const nsecs_t now = systemTime();
2010 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002011
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2013 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002014 if (!displayDevice->isDisplayOn()) {
2015 continue;
2016 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 const auto hwcId = displayDevice->getHwcDisplayId();
2018 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002019 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002020 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002021 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002022 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002023 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2024 sp<Fence> releaseFence = Fence::NO_FENCE;
2025 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
2026 releaseFence = displayDevice->getClientTargetAcquireFence();
2027 } else {
2028 auto hwcLayer = layer->getHwcLayer(hwcId);
2029 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002030 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002031 layer->onLayerDisplayed(releaseFence);
2032 }
2033 if (hwcId >= 0) {
2034 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002035 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002036 }
2037
Mathias Agopiana44b0412011-10-16 18:46:35 -07002038 mLastSwapBufferTime = systemTime() - now;
2039 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002040
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002041 // |mStateLock| not needed as we are on the main thread
2042 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002043 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2044 logFrameStats();
2045 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002046}
2047
Mathias Agopian87baae12012-07-31 12:38:26 -07002048void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002049{
Mathias Agopian841cde52012-03-01 15:44:37 -08002050 ATRACE_CALL();
2051
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002052 // here we keep a copy of the drawing state (that is the state that's
2053 // going to be overwritten by handleTransactionLocked()) outside of
2054 // mStateLock so that the side-effects of the State assignment
2055 // don't happen with mStateLock held (which can cause deadlocks).
2056 State drawingState(mDrawingState);
2057
Mathias Agopianca4d3602011-05-19 15:38:14 -07002058 Mutex::Autolock _l(mStateLock);
2059 const nsecs_t now = systemTime();
2060 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002061
Mathias Agopianca4d3602011-05-19 15:38:14 -07002062 // Here we're guaranteed that some transaction flags are set
2063 // so we can call handleTransactionLocked() unconditionally.
2064 // We call getTransactionFlags(), which will also clear the flags,
2065 // with mStateLock held to guarantee that mCurrentState won't change
2066 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002067
Mathias Agopiane57f2922012-08-09 16:29:12 -07002068 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002069 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002070
Mathias Agopianca4d3602011-05-19 15:38:14 -07002071 mLastTransactionTime = systemTime() - now;
2072 mDebugInTransaction = 0;
2073 invalidateHwcGeometry();
2074 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002075}
2076
Mathias Agopian87baae12012-07-31 12:38:26 -07002077void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002078{
Dan Stoza7dde5992015-05-22 09:51:44 -07002079 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002080 mCurrentState.traverseInZOrder([](Layer* layer) {
2081 layer->notifyAvailableFrames();
2082 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002083
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002084 /*
2085 * Traversal of the children
2086 * (perform the transaction for each of them if needed)
2087 */
2088
Mathias Agopian3559b072012-08-15 13:46:03 -07002089 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002090 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002091 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002092 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093
2094 const uint32_t flags = layer->doTransaction(0);
2095 if (flags & Layer::eVisibleRegion)
2096 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002097 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002098 }
2099
2100 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002101 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002102 */
2103
Mathias Agopiane57f2922012-08-09 16:29:12 -07002104 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002105 // here we take advantage of Vector's copy-on-write semantics to
2106 // improve performance by skipping the transaction entirely when
2107 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002108 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2109 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002110 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002111 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002112 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002113 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002114
2115 // find the displays that were removed
2116 // (ie: in drawing state but not in current state)
2117 // also handle displays that changed
2118 // (ie: displays that are in both lists)
2119 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002120 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2121 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002122 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002123 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002124 // Call makeCurrent() on the primary display so we can
2125 // be sure that nothing associated with this display
2126 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002127 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002128 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002129 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002130 if (hw != NULL)
2131 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002132 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002133 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002134 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002135 } else {
2136 ALOGW("trying to remove the main display");
2137 }
2138 } else {
2139 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002140 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002141 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002142 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2143 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002144 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002145 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002146 // recreating the DisplayDevice, so we just remove it
2147 // from the drawing state, so that it get re-added
2148 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002149 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002150 if (hw != NULL)
2151 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002152 mDisplays.removeItem(display);
2153 mDrawingState.displays.removeItemsAt(i);
2154 dc--; i--;
2155 // at this point we must loop to the next item
2156 continue;
2157 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002158
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002159 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002160 if (disp != NULL) {
2161 if (state.layerStack != draw[i].layerStack) {
2162 disp->setLayerStack(state.layerStack);
2163 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002164 if ((state.orientation != draw[i].orientation)
2165 || (state.viewport != draw[i].viewport)
2166 || (state.frame != draw[i].frame))
2167 {
2168 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002169 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002170 }
Michael Lentine47e45402014-07-18 15:34:25 -07002171 if (state.width != draw[i].width || state.height != draw[i].height) {
2172 disp->setDisplaySize(state.width, state.height);
2173 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002174 }
2175 }
2176 }
2177
2178 // find displays that were added
2179 // (ie: in current state but not in drawing state)
2180 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002181 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002182 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002183
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002184 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002185 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002186 sp<IGraphicBufferProducer> bqProducer;
2187 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002188 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002189
Dan Stoza9e56aa02015-11-02 13:00:03 -08002190 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002191 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002192 // Virtual displays without a surface are dormant:
2193 // they have external state (layer stack, projection,
2194 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002195 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002196
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002197 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002198 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002199 int width = 0;
2200 int status = state.surface->query(
2201 NATIVE_WINDOW_WIDTH, &width);
2202 ALOGE_IF(status != NO_ERROR,
2203 "Unable to query width (%d)", status);
2204 int height = 0;
2205 status = state.surface->query(
2206 NATIVE_WINDOW_HEIGHT, &height);
2207 ALOGE_IF(status != NO_ERROR,
2208 "Unable to query height (%d)", status);
2209 int intFormat = 0;
2210 status = state.surface->query(
2211 NATIVE_WINDOW_FORMAT, &intFormat);
2212 ALOGE_IF(status != NO_ERROR,
2213 "Unable to query format (%d)", status);
2214 auto format = static_cast<android_pixel_format_t>(
2215 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002216
Dan Stoza8cf150a2016-08-02 10:27:31 -07002217 mHwc->allocateVirtualDisplay(width, height, &format,
2218 &hwcId);
2219 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002220
Dan Stoza5cf424b2016-05-20 14:02:39 -07002221 // TODO: Plumb requested format back up to consumer
2222
Dan Stoza9e56aa02015-11-02 13:00:03 -08002223 sp<VirtualDisplaySurface> vds =
2224 new VirtualDisplaySurface(*mHwc,
2225 hwcId, state.surface, bqProducer,
2226 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002227
2228 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002229 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002230 }
2231 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002232 ALOGE_IF(state.surface!=NULL,
2233 "adding a supported display, but rendering "
2234 "surface is provided (%p), ignoring it",
2235 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002236
2237 hwcId = state.type;
2238 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2239 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002240 }
2241
2242 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002243 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002244 sp<DisplayDevice> hw =
2245 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2246 dispSurface, producer,
2247 mRenderEngine->getEGLConfig(),
2248 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002249 hw->setLayerStack(state.layerStack);
2250 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002251 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002252 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002253 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002254 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002255 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002256 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002257 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002258 }
2259 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002260 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002261 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002262
Mathias Agopian84300952012-11-21 16:02:13 -08002263 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2264 // The transform hint might have changed for some layers
2265 // (either because a display has changed, or because a layer
2266 // as changed).
2267 //
2268 // Walk through all the layers in currentLayers,
2269 // and update their transform hint.
2270 //
2271 // If a layer is visible only on a single display, then that
2272 // display is used to calculate the hint, otherwise we use the
2273 // default display.
2274 //
2275 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2276 // the hint is set before we acquire a buffer from the surface texture.
2277 //
2278 // NOTE: layer transactions have taken place already, so we use their
2279 // drawing state. However, SurfaceFlinger's own transaction has not
2280 // happened yet, so we must use the current state layer list
2281 // (soon to become the drawing state list).
2282 //
2283 sp<const DisplayDevice> disp;
2284 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002285 bool first = true;
2286 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002287 // NOTE: we rely on the fact that layers are sorted by
2288 // layerStack first (so we don't have to traverse the list
2289 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002290 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002291 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002292 currentlayerStack = layerStack;
2293 // figure out if this layerstack is mirrored
2294 // (more than one display) if so, pick the default display,
2295 // if not, pick the only display it's on.
2296 disp.clear();
2297 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2298 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002299 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002300 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002301 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002302 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002303 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002304 break;
2305 }
2306 }
2307 }
2308 }
Chet Haase91d25932013-04-11 15:24:55 -07002309 if (disp == NULL) {
2310 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2311 // redraw after transform hint changes. See bug 8508397.
2312
2313 // could be null when this layer is using a layerStack
2314 // that is not visible on any display. Also can occur at
2315 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002316 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002317 }
Chet Haase91d25932013-04-11 15:24:55 -07002318 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002319
2320 first = false;
2321 });
Mathias Agopian84300952012-11-21 16:02:13 -08002322 }
2323
2324
Mathias Agopian3559b072012-08-15 13:46:03 -07002325 /*
2326 * Perform our own transaction if needed
2327 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002328
2329 if (mLayersAdded) {
2330 mLayersAdded = false;
2331 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002332 mVisibleRegionsDirty = true;
2333 }
2334
2335 // some layers might have been removed, so
2336 // we need to update the regions they're exposing.
2337 if (mLayersRemoved) {
2338 mLayersRemoved = false;
2339 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002340 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002341 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002342 // this layer is not visible anymore
2343 // TODO: we could traverse the tree from front to back and
2344 // compute the actual visible region
2345 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002346 Region visibleReg;
2347 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002348 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002349 }
Robert Carr2047fae2016-11-28 14:09:09 -08002350 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002351 }
2352
2353 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002354
2355 updateCursorAsync();
2356}
2357
2358void SurfaceFlinger::updateCursorAsync()
2359{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002360 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2361 auto& displayDevice = mDisplays[displayId];
2362 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002363 continue;
2364 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002365
2366 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2367 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002368 }
2369 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002370}
2371
2372void SurfaceFlinger::commitTransaction()
2373{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002374 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002375 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002376 for (const auto& l : mLayersPendingRemoval) {
2377 recordBufferingStats(l->getName().string(),
2378 l->getOccupancyHistory(true));
2379 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002380 }
2381 mLayersPendingRemoval.clear();
2382 }
2383
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002384 // If this transaction is part of a window animation then the next frame
2385 // we composite should be considered an animation as well.
2386 mAnimCompositionPending = mAnimTransactionPending;
2387
Mathias Agopian4fec8732012-06-29 14:12:52 -07002388 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002389 mDrawingState.traverseInZOrder([](Layer* layer) {
2390 layer->commitChildList();
2391 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002392 mTransactionPending = false;
2393 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002394 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002395}
2396
Chia-I Wuab0c3192017-08-01 11:29:00 -07002397void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002398 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002399{
Mathias Agopian841cde52012-03-01 15:44:37 -08002400 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002401 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002402
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002403 Region aboveOpaqueLayers;
2404 Region aboveCoveredLayers;
2405 Region dirty;
2406
Mathias Agopian87baae12012-07-31 12:38:26 -07002407 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002408
Robert Carr2047fae2016-11-28 14:09:09 -08002409 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002410 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002411 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002412
Jesse Hall01e29052013-02-19 16:13:35 -08002413 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002414 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002415 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002416
Mathias Agopianab028732010-03-16 16:41:46 -07002417 /*
2418 * opaqueRegion: area of a surface that is fully opaque.
2419 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002420 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002421
2422 /*
2423 * visibleRegion: area of a surface that is visible on screen
2424 * and not fully transparent. This is essentially the layer's
2425 * footprint minus the opaque regions above it.
2426 * Areas covered by a translucent surface are considered visible.
2427 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002428 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002429
2430 /*
2431 * coveredRegion: area of a surface that is covered by all
2432 * visible regions above it (which includes the translucent areas).
2433 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002434 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002435
Jesse Halla8026d22012-09-25 13:25:04 -07002436 /*
2437 * transparentRegion: area of a surface that is hinted to be completely
2438 * transparent. This is only used to tell when the layer has no visible
2439 * non-transparent regions and can be removed from the layer list. It
2440 * does not affect the visibleRegion of this layer or any layers
2441 * beneath it. The hint may not be correct if apps don't respect the
2442 * SurfaceView restrictions (which, sadly, some don't).
2443 */
2444 Region transparentRegion;
2445
Mathias Agopianab028732010-03-16 16:41:46 -07002446
2447 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002448 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002449 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002450 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002451 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002452 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002453 if (!visibleRegion.isEmpty()) {
2454 // Remove the transparent area from the visible region
2455 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002456 if (tr.preserveRects()) {
2457 // transform the transparent region
2458 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002459 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002460 // transformation too complex, can't do the
2461 // transparent region optimization.
2462 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002463 }
Mathias Agopianab028732010-03-16 16:41:46 -07002464 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465
Mathias Agopianab028732010-03-16 16:41:46 -07002466 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002467 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002468 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002469 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2470 // the opaque region is the layer's footprint
2471 opaqueRegion = visibleRegion;
2472 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473 }
2474 }
2475
Mathias Agopianab028732010-03-16 16:41:46 -07002476 // Clip the covered region to the visible region
2477 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2478
2479 // Update aboveCoveredLayers for next (lower) layer
2480 aboveCoveredLayers.orSelf(visibleRegion);
2481
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482 // subtract the opaque region covered by the layers above us
2483 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484
2485 // compute this layer's dirty region
2486 if (layer->contentDirty) {
2487 // we need to invalidate the whole region
2488 dirty = visibleRegion;
2489 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002490 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491 layer->contentDirty = false;
2492 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002493 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002494 * the exposed region consists of two components:
2495 * 1) what's VISIBLE now and was COVERED before
2496 * 2) what's EXPOSED now less what was EXPOSED before
2497 *
2498 * note that (1) is conservative, we start with the whole
2499 * visible region but only keep what used to be covered by
2500 * something -- which mean it may have been exposed.
2501 *
2502 * (2) handles areas that were not covered by anything but got
2503 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002504 */
Mathias Agopianab028732010-03-16 16:41:46 -07002505 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002506 const Region oldVisibleRegion = layer->visibleRegion;
2507 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002508 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2509 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510 }
2511 dirty.subtractSelf(aboveOpaqueLayers);
2512
2513 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002514 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515
Mathias Agopianab028732010-03-16 16:41:46 -07002516 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002518
Jesse Halla8026d22012-09-25 13:25:04 -07002519 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520 layer->setVisibleRegion(visibleRegion);
2521 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002522 layer->setVisibleNonTransparentRegion(
2523 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002524 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002525
Mathias Agopian87baae12012-07-31 12:38:26 -07002526 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002527}
2528
Chia-I Wuab0c3192017-08-01 11:29:00 -07002529void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002530 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002531 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002532 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002533 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002534 }
2535 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002536}
2537
Dan Stoza6b9454d2014-11-07 16:00:59 -08002538bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002540 ALOGV("handlePageFlip");
2541
Brian Andersond6927fb2016-07-23 23:37:30 -07002542 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543
Mathias Agopian4fec8732012-06-29 14:12:52 -07002544 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002545 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002546 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002547
2548 // Store the set of layers that need updates. This set must not change as
2549 // buffers are being latched, as this could result in a deadlock.
2550 // Example: Two producers share the same command stream and:
2551 // 1.) Layer 0 is latched
2552 // 2.) Layer 0 gets a new frame
2553 // 2.) Layer 1 gets a new frame
2554 // 3.) Layer 1 is latched.
2555 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2556 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002557 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002558 if (layer->hasQueuedFrame()) {
2559 frameQueued = true;
2560 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002561 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002562 } else {
2563 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002564 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002565 } else {
2566 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002567 }
Robert Carr2047fae2016-11-28 14:09:09 -08002568 });
2569
Dan Stoza9e56aa02015-11-02 13:00:03 -08002570 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002571 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002572 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002573 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002574 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002575 newDataLatched = true;
2576 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002577 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002578
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002579 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002580
2581 // If we will need to wake up at some time in the future to deal with a
2582 // queued frame that shouldn't be displayed during this vsync period, wake
2583 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002584 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002585 signalLayerUpdate();
2586 }
2587
2588 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002589 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590}
2591
Mathias Agopianad456f92011-01-13 17:53:01 -08002592void SurfaceFlinger::invalidateHwcGeometry()
2593{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002594 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002595}
2596
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002597
Fabien Sanglard830b8472016-11-30 16:35:58 -08002598void SurfaceFlinger::doDisplayComposition(
2599 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002600 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601{
Dan Stoza71433162014-02-04 16:22:36 -08002602 // We only need to actually compose the display if:
2603 // 1) It is being handled by hardware composer, which may need this to
2604 // keep its virtual display state machine in sync, or
2605 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002606 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002607 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002608 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002609 return;
2610 }
2611
Dan Stoza9e56aa02015-11-02 13:00:03 -08002612 ALOGV("doDisplayComposition");
2613
Mathias Agopian87baae12012-07-31 12:38:26 -07002614 Region dirtyRegion(inDirtyRegion);
2615
Mathias Agopianb8a55602009-06-26 19:06:36 -07002616 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002617 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618
Fabien Sanglard830b8472016-11-30 16:35:58 -08002619 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002620 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002621 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2622 // takes a rectangle, we must make sure to update that whole
2623 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002624 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002625 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002626 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002627 // We need to redraw the rectangle that will be updated
2628 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002629 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002630 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002631 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002632 } else {
2633 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002634 dirtyRegion.set(displayDevice->bounds());
2635 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636 }
2637 }
2638
Fabien Sanglard830b8472016-11-30 16:35:58 -08002639 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002641 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002642 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002643
2644 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002645 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646}
2647
Dan Stoza9e56aa02015-11-02 13:00:03 -08002648bool SurfaceFlinger::doComposeSurfaces(
2649 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002650{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002651 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002652
Dan Stoza9e56aa02015-11-02 13:00:03 -08002653 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002654
2655 mat4 oldColorMatrix;
2656 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2657 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2658 if (applyColorMatrix) {
2659 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2660 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2661 }
2662
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2664 if (hasClientComposition) {
2665 ALOGV("hasClientComposition");
2666
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002667#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01002668 mRenderEngine->setWideColor(
2669 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2670 mRenderEngine->setColorMode(mForceNativeColorMode ?
2671 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002672#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002673 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002674 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002675 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002676 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002677
2678 // |mStateLock| not needed as we are on the main thread
2679 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002680 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2681 }
2682 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002683 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002684
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002685 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002686 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2687 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002688 // when using overlays, we assume a fully transparent framebuffer
2689 // NOTE: we could reduce how much we need to clear, for instance
2690 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002691 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002692 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002694 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002695 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002696 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002697
2698 // we remove the scissor part
2699 // we're left with the letterbox region
2700 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002701 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002702
2703 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002704 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002705
2706 // but limit it to the dirty region
2707 region.andSelf(dirty);
2708
Mathias Agopianb9494d52012-04-18 02:28:45 -07002709 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002710 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002711 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002712 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002713 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002714 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002715
Dan Stoza9e56aa02015-11-02 13:00:03 -08002716 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002717 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002718 // scissor on the main display. It should never be needed
2719 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002720 const Rect& bounds(displayDevice->getBounds());
2721 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002722 if (scissor != bounds) {
2723 // scissor doesn't match the screen's dimensions, so we
2724 // need to clear everything outside of it and enable
2725 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002726
Mathias Agopianf45c5102012-10-24 16:29:17 -07002727 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002728 const uint32_t height = displayDevice->getHeight();
2729 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002730 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002731 }
2732 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002733 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002734
Mathias Agopian85d751c2012-08-29 16:59:24 -07002735 /*
2736 * and then, render the layers targeted at the framebuffer
2737 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002738
Dan Stoza9e56aa02015-11-02 13:00:03 -08002739 ALOGV("Rendering client layers");
2740 const Transform& displayTransform = displayDevice->getTransform();
2741 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002742 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002743 bool firstLayer = true;
2744 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2745 const Region clip(dirty.intersect(
2746 displayTransform.transform(layer->visibleRegion)));
2747 ALOGV("Layer: %s", layer->getName().string());
2748 ALOGV(" Composition type: %s",
2749 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002750 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002751 switch (layer->getCompositionType(hwcId)) {
2752 case HWC2::Composition::Cursor:
2753 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002754 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002755 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002756 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002757 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002758 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002759 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002760 // never clear the very first layer since we're
2761 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002762 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002763 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002764 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002765 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002766 case HWC2::Composition::Client: {
2767 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002768 break;
2769 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002770 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002771 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002772 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002773 } else {
2774 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002775 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002776 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002777 }
2778 } else {
2779 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002780 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002781 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002782 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002783 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002784 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002785 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002786 }
2787 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002788
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002789 if (applyColorMatrix) {
2790 getRenderEngine().setupColorTransform(oldColorMatrix);
2791 }
2792
Mathias Agopianf45c5102012-10-24 16:29:17 -07002793 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002794 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002795 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796}
2797
Fabien Sanglard830b8472016-11-30 16:35:58 -08002798void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2799 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002800 RenderEngine& engine(getRenderEngine());
2801 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802}
2803
Dan Stoza7d89d062015-04-30 13:29:25 -07002804status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002805 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002806 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002807 const sp<Layer>& lbc,
2808 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002809{
Dan Stoza7d89d062015-04-30 13:29:25 -07002810 // add this layer to the current state list
2811 {
2812 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002813 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002814 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2815 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002816 return NO_MEMORY;
2817 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002818 if (parent == nullptr) {
2819 mCurrentState.layersSortedByZ.add(lbc);
2820 } else {
chaviwc9674332017-08-28 12:32:18 -07002821 bool found = false;
2822 mCurrentState.traverseInZOrder([&](Layer* layer) {
2823 if (layer == parent.get()) {
2824 found = true;
2825 }
2826 });
2827
2828 if (!found) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002829 ALOGE("addClientLayer called with a removed parent");
2830 return NAME_NOT_FOUND;
2831 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002832 parent->addChild(lbc);
2833 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002834
Dan Stoza7d89d062015-04-30 13:29:25 -07002835 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002836 mLayersAdded = true;
2837 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002838 }
2839
Mathias Agopian96f08192010-06-02 23:28:45 -07002840 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002841 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002842
Dan Stoza7d89d062015-04-30 13:29:25 -07002843 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002844}
2845
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002846status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002847 Mutex::Autolock _l(mStateLock);
2848
Robert Carr1f0a16a2016-10-24 16:27:39 -07002849 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002850 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002851 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002852 if (topLevelOnly) {
2853 return NO_ERROR;
2854 }
2855
Chia-I Wu98f1c102017-05-30 14:54:08 -07002856 sp<Layer> ancestor = p;
2857 while (ancestor->getParent() != nullptr) {
2858 ancestor = ancestor->getParent();
2859 }
2860 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2861 ALOGE("removeLayer called with a layer whose parent has been removed");
2862 return NAME_NOT_FOUND;
2863 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002864
2865 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002866 } else {
2867 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002868 }
2869
Robert Carr136e2f62017-02-08 17:54:29 -08002870 // As a matter of normal operation, the LayerCleaner will produce a second
2871 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2872 // so we will succeed in promoting it, but it's already been removed
2873 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2874 // otherwise something has gone wrong and we are leaking the layer.
2875 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002876 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2877 layer->getName().string(),
2878 (p != nullptr) ? p->getName().string() : "no-parent");
2879 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002880 } else if (index < 0) {
2881 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002882 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883
Chia-I Wuc6657022017-08-15 11:18:17 -07002884 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002885 mLayersPendingRemoval.add(layer);
2886 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002887 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002888 setTransactionFlags(eTransactionNeeded);
2889 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890}
2891
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002892uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002893 return android_atomic_release_load(&mTransactionFlags);
2894}
2895
Mathias Agopian3f844832013-08-07 21:24:32 -07002896uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2898}
2899
Mathias Agopian3f844832013-08-07 21:24:32 -07002900uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002901 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2902 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002903 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904 }
2905 return old;
2906}
2907
Mathias Agopian8b33f032012-07-24 20:43:54 -07002908void SurfaceFlinger::setTransactionState(
2909 const Vector<ComposerState>& state,
2910 const Vector<DisplayState>& displays,
2911 uint32_t flags)
2912{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002913 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002914 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002915 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002916
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002917 if (flags & eAnimation) {
2918 // For window updates that are part of an animation we must wait for
2919 // previous animation "frames" to be handled.
2920 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002921 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002922 if (CC_UNLIKELY(err != NO_ERROR)) {
2923 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002924 // caller after a few seconds.
2925 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2926 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002927 mAnimTransactionPending = false;
2928 break;
2929 }
2930 }
2931 }
2932
Mathias Agopiane57f2922012-08-09 16:29:12 -07002933 size_t count = displays.size();
2934 for (size_t i=0 ; i<count ; i++) {
2935 const DisplayState& s(displays[i]);
2936 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002937 }
2938
Mathias Agopiane57f2922012-08-09 16:29:12 -07002939 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002940 for (size_t i=0 ; i<count ; i++) {
2941 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002942 // Here we need to check that the interface we're given is indeed
2943 // one of our own. A malicious client could give us a NULL
2944 // IInterface, or one of its own or even one of our own but a
2945 // different type. All these situations would cause us to crash.
2946 //
2947 // NOTE: it would be better to use RTTI as we could directly check
2948 // that we have a Client*. however, RTTI is disabled in Android.
2949 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002950 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002951 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002952 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002953 sp<Client> client( static_cast<Client *>(s.client.get()) );
2954 transactionFlags |= setClientStateLocked(client, s.state);
2955 }
2956 }
2957 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002958 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002959
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002960 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2961 // anyway. This can be used as a flush mechanism for previous async transactions.
2962 // Empty animation transaction can be used to simulate back-pressure, so also force a
2963 // transaction for empty animation transactions.
2964 if (transactionFlags == 0 &&
2965 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002966 transactionFlags = eTransactionNeeded;
2967 }
2968
Mathias Agopian386aa982011-11-07 21:58:03 -08002969 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002970 if (mInterceptor.isEnabled()) {
2971 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2972 }
Irvel468051e2016-06-13 16:44:44 -07002973
Mathias Agopian386aa982011-11-07 21:58:03 -08002974 // this triggers the transaction
2975 setTransactionFlags(transactionFlags);
2976
2977 // if this is a synchronous transaction, wait for it to take effect
2978 // before returning.
2979 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002980 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002981 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002982 if (flags & eAnimation) {
2983 mAnimTransactionPending = true;
2984 }
2985 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002986 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2987 if (CC_UNLIKELY(err != NO_ERROR)) {
2988 // just in case something goes wrong in SF, return to the
2989 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002990 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2991 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002992 break;
2993 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002994 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002995 }
2996}
2997
Mathias Agopiane57f2922012-08-09 16:29:12 -07002998uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2999{
Jesse Hall9a143922012-10-04 16:29:19 -07003000 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3001 if (dpyIdx < 0)
3002 return 0;
3003
Mathias Agopiane57f2922012-08-09 16:29:12 -07003004 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003005 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003006 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003007 const uint32_t what = s.what;
3008 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003009 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003010 disp.surface = s.surface;
3011 flags |= eDisplayTransactionNeeded;
3012 }
3013 }
3014 if (what & DisplayState::eLayerStackChanged) {
3015 if (disp.layerStack != s.layerStack) {
3016 disp.layerStack = s.layerStack;
3017 flags |= eDisplayTransactionNeeded;
3018 }
3019 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003020 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003021 if (disp.orientation != s.orientation) {
3022 disp.orientation = s.orientation;
3023 flags |= eDisplayTransactionNeeded;
3024 }
3025 if (disp.frame != s.frame) {
3026 disp.frame = s.frame;
3027 flags |= eDisplayTransactionNeeded;
3028 }
3029 if (disp.viewport != s.viewport) {
3030 disp.viewport = s.viewport;
3031 flags |= eDisplayTransactionNeeded;
3032 }
3033 }
Michael Lentine47e45402014-07-18 15:34:25 -07003034 if (what & DisplayState::eDisplaySizeChanged) {
3035 if (disp.width != s.width) {
3036 disp.width = s.width;
3037 flags |= eDisplayTransactionNeeded;
3038 }
3039 if (disp.height != s.height) {
3040 disp.height = s.height;
3041 flags |= eDisplayTransactionNeeded;
3042 }
3043 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003044 }
3045 return flags;
3046}
3047
3048uint32_t SurfaceFlinger::setClientStateLocked(
3049 const sp<Client>& client,
3050 const layer_state_t& s)
3051{
3052 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003053 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003054 if (layer != 0) {
3055 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003056 bool geometryAppliesWithResize =
3057 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003058 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003059 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003060 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003061 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003062 }
3063 if (what & layer_state_t::eLayerChanged) {
3064 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003065 const auto& p = layer->getParent();
3066 if (p == nullptr) {
3067 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3068 if (layer->setLayer(s.z) && idx >= 0) {
3069 mCurrentState.layersSortedByZ.removeAt(idx);
3070 mCurrentState.layersSortedByZ.add(layer);
3071 // we need traversal (state changed)
3072 // AND transaction (list changed)
3073 flags |= eTransactionNeeded|eTraversalNeeded;
3074 }
3075 } else {
3076 if (p->setChildLayer(layer, s.z)) {
3077 flags |= eTransactionNeeded|eTraversalNeeded;
3078 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003079 }
3080 }
Robert Carrdb66e622017-04-10 16:55:57 -07003081 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003082 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003083 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003084 mCurrentState.layersSortedByZ.removeAt(idx);
3085 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003086 flags |= eTransactionNeeded|eTraversalNeeded;
3087 }
3088 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003089 if (what & layer_state_t::eSizeChanged) {
3090 if (layer->setSize(s.w, s.h)) {
3091 flags |= eTraversalNeeded;
3092 }
3093 }
3094 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003095 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003096 flags |= eTraversalNeeded;
3097 }
chaviw13fdc492017-06-27 12:40:18 -07003098 if (what & layer_state_t::eColorChanged) {
3099 if (layer->setColor(s.color))
3100 flags |= eTraversalNeeded;
3101 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003102 if (what & layer_state_t::eMatrixChanged) {
3103 if (layer->setMatrix(s.matrix))
3104 flags |= eTraversalNeeded;
3105 }
3106 if (what & layer_state_t::eTransparentRegionChanged) {
3107 if (layer->setTransparentRegionHint(s.transparentRegion))
3108 flags |= eTraversalNeeded;
3109 }
Dan Stoza23116082015-06-18 14:58:39 -07003110 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003111 if (layer->setFlags(s.flags, s.mask))
3112 flags |= eTraversalNeeded;
3113 }
3114 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003115 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003116 flags |= eTraversalNeeded;
3117 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003118 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003119 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003120 flags |= eTraversalNeeded;
3121 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003122 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003123 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003124 // We only allow setting layer stacks for top level layers,
3125 // everything else inherits layer stack from its parent.
3126 if (layer->hasParent()) {
3127 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3128 layer->getName().string());
3129 } else if (idx < 0) {
3130 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3131 "that also does not appear in the top level layer list. Something"
3132 " has gone wrong.", layer->getName().string());
3133 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003134 mCurrentState.layersSortedByZ.removeAt(idx);
3135 mCurrentState.layersSortedByZ.add(layer);
3136 // we need traversal (state changed)
3137 // AND transaction (list changed)
3138 flags |= eTransactionNeeded|eTraversalNeeded;
3139 }
3140 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003141 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003142 if (s.barrierHandle != nullptr) {
3143 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3144 } else if (s.barrierGbp != nullptr) {
3145 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3146 if (authenticateSurfaceTextureLocked(gbp)) {
3147 const auto& otherLayer =
3148 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3149 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3150 } else {
3151 ALOGE("Attempt to defer transaction to to an"
3152 " unrecognized GraphicBufferProducer");
3153 }
3154 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003155 // We don't trigger a traversal here because if no other state is
3156 // changed, we don't want this to cause any more work
3157 }
chaviwf1961f72017-09-18 16:41:07 -07003158 if (what & layer_state_t::eReparent) {
3159 if (layer->reparent(s.parentHandleForChild)) {
chaviw06178942017-07-27 10:25:59 -07003160 flags |= eTransactionNeeded|eTraversalNeeded;
3161 }
3162 }
Robert Carr1db73f62016-12-21 12:58:51 -08003163 if (what & layer_state_t::eReparentChildren) {
3164 if (layer->reparentChildren(s.reparentHandle)) {
3165 flags |= eTransactionNeeded|eTraversalNeeded;
3166 }
3167 }
Robert Carr9524cb32017-02-13 11:32:32 -08003168 if (what & layer_state_t::eDetachChildren) {
3169 layer->detachChildren();
3170 }
Robert Carrc3574f72016-03-24 12:19:32 -07003171 if (what & layer_state_t::eOverrideScalingModeChanged) {
3172 layer->setOverrideScalingMode(s.overrideScalingMode);
3173 // We don't trigger a traversal here because if no other state is
3174 // changed, we don't want this to cause any more work
3175 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003176 }
3177 return flags;
3178}
3179
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003180status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003181 const String8& name,
3182 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003183 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003184 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3185 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003187 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003188 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003189 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003190 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003191 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003192
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003193 status_t result = NO_ERROR;
3194
3195 sp<Layer> layer;
3196
Cody Northropbc755282017-03-31 12:00:08 -06003197 String8 uniqueName = getUniqueLayerName(name);
3198
Mathias Agopian3165cc22012-08-08 19:42:09 -07003199 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3200 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003201 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003202 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003203 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204 break;
chaviw13fdc492017-06-27 12:40:18 -07003205 case ISurfaceComposerClient::eFXSurfaceColor:
3206 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003207 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003208 handle, gbp, &layer);
3209 break;
3210 default:
3211 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212 break;
3213 }
3214
Dan Stoza7d89d062015-04-30 13:29:25 -07003215 if (result != NO_ERROR) {
3216 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003217 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003218
Chia-I Wuab0c3192017-08-01 11:29:00 -07003219 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3220 // TODO b/64227542
3221 if (windowType == 441731) {
3222 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3223 layer->setPrimaryDisplayOnly();
3224 }
3225
Albert Chaulk479c60c2017-01-27 14:21:34 -05003226 layer->setInfo(windowType, ownerUid);
3227
Robert Carr1f0a16a2016-10-24 16:27:39 -07003228 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003229 if (result != NO_ERROR) {
3230 return result;
3231 }
Irvelffc9efc2016-07-27 15:16:37 -07003232 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003233
3234 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003235 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236}
3237
Cody Northropbc755282017-03-31 12:00:08 -06003238String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3239{
3240 bool matchFound = true;
3241 uint32_t dupeCounter = 0;
3242
3243 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3244 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3245
3246 // Loop over layers until we're sure there is no matching name
3247 while (matchFound) {
3248 matchFound = false;
3249 mDrawingState.traverseInZOrder([&](Layer* layer) {
3250 if (layer->getName() == uniqueName) {
3251 matchFound = true;
3252 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3253 }
3254 });
3255 }
3256
3257 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3258
3259 return uniqueName;
3260}
3261
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003262status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3263 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3264 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265{
3266 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003267 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268 case PIXEL_FORMAT_TRANSPARENT:
3269 case PIXEL_FORMAT_TRANSLUCENT:
3270 format = PIXEL_FORMAT_RGBA_8888;
3271 break;
3272 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003273 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274 break;
3275 }
3276
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003277 *outLayer = new Layer(this, client, name, w, h, flags);
3278 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3279 if (err == NO_ERROR) {
3280 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003281 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003282 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003283
3284 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3285 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286}
3287
chaviw13fdc492017-06-27 12:40:18 -07003288status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003289 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3290 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291{
chaviw13fdc492017-06-27 12:40:18 -07003292 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003293 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003294 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003295 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003296}
3297
Mathias Agopianac9fa422013-02-11 16:40:36 -08003298status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003299{
Robert Carr9524cb32017-02-13 11:32:32 -08003300 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003301 status_t err = NO_ERROR;
3302 sp<Layer> l(client->getLayerUser(handle));
3303 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003304 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003305 err = removeLayer(l);
3306 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3307 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003308 }
3309 return err;
3310}
3311
Mathias Agopian13127d82013-03-05 17:47:11 -08003312status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003313{
Mathias Agopian67106042013-03-14 19:18:13 -07003314 // called by ~LayerCleaner() when all references to the IBinder (handle)
3315 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003316 sp<Layer> l = layer.promote();
3317 if (l == nullptr) {
3318 // The layer has already been removed, carry on
3319 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003320 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003321 // If we have a parent, then we can continue to live as long as it does.
3322 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003323}
3324
Mathias Agopianb60314a2012-04-10 22:09:54 -07003325// ---------------------------------------------------------------------------
3326
Andy McFadden13a082e2012-08-24 10:16:42 -07003327void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003328 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003329 Vector<ComposerState> state;
3330 Vector<DisplayState> displays;
3331 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003332 d.what = DisplayState::eDisplayProjectionChanged |
3333 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003334 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003335 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003336 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003337 d.frame.makeInvalid();
3338 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003339 d.width = 0;
3340 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003341 displays.add(d);
3342 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003343 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3344 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003345
Dan Stoza9e56aa02015-11-02 13:00:03 -08003346 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3347 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003348 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003349
Brian Andersond0010582017-03-07 13:20:31 -08003350 // Use phase of 0 since phase is not known.
3351 // Use latency of 0, which will snap to the ideal latency.
3352 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003353}
3354
3355void SurfaceFlinger::initializeDisplays() {
3356 class MessageScreenInitialized : public MessageBase {
3357 SurfaceFlinger* flinger;
3358 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003359 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003360 virtual bool handler() {
3361 flinger->onInitializeDisplays();
3362 return true;
3363 }
3364 };
3365 sp<MessageBase> msg = new MessageScreenInitialized(this);
3366 postMessageAsync(msg); // we may be called from main thread, use async message
3367}
3368
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003369void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003370 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003371 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3372 this);
3373 int32_t type = hw->getDisplayType();
3374 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003375
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003376 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003377 return;
3378 }
3379
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003380 hw->setPowerMode(mode);
3381 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3382 ALOGW("Trying to set power mode for virtual display");
3383 return;
3384 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003385
Irvelffc9efc2016-07-27 15:16:37 -07003386 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003387 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003388 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3389 if (idx < 0) {
3390 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3391 return;
3392 }
3393 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3394 }
3395
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003396 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003397 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003398 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003399 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3400 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003401 // FIXME: eventthread only knows about the main display right now
3402 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003403 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003404 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003405
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003406 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003407 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003408 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003409
3410 struct sched_param param = {0};
3411 param.sched_priority = 1;
3412 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3413 ALOGW("Couldn't set SCHED_FIFO on display on");
3414 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003415 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003416 // Turn off the display
3417 struct sched_param param = {0};
3418 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3419 ALOGW("Couldn't set SCHED_OTHER on display off");
3420 }
3421
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003422 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003423 disableHardwareVsync(true); // also cancels any in-progress resync
3424
Mathias Agopiancde87a32012-09-13 14:09:01 -07003425 // FIXME: eventthread only knows about the main display right now
3426 mEventThread->onScreenReleased();
3427 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003428
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003429 getHwComposer().setPowerMode(type, mode);
3430 mVisibleRegionsDirty = true;
3431 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003432 } else if (mode == HWC_POWER_MODE_DOZE ||
3433 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003434 // Update display while dozing
3435 getHwComposer().setPowerMode(type, mode);
3436 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3437 // FIXME: eventthread only knows about the main display right now
3438 mEventThread->onScreenAcquired();
3439 resyncToHardwareVsync(true);
3440 }
3441 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3442 // Leave display going to doze
3443 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3444 disableHardwareVsync(true); // also cancels any in-progress resync
3445 // FIXME: eventthread only knows about the main display right now
3446 mEventThread->onScreenReleased();
3447 }
3448 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003449 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003450 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003451 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003452 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003453}
3454
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003455void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3456 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003457 SurfaceFlinger& mFlinger;
3458 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003459 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003460 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003461 MessageSetPowerMode(SurfaceFlinger& flinger,
3462 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3463 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003464 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003465 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003466 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003467 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003468 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003469 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003470 ALOGW("Attempt to set power mode = %d for virtual display",
3471 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003472 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003473 mFlinger.setPowerModeInternal(
3474 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003475 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003476 return true;
3477 }
3478 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003479 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003480 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003481}
3482
3483// ---------------------------------------------------------------------------
3484
Vishnu Nair35798872017-10-06 16:00:36 -07003485status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003486 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003487
Mathias Agopianbd115332013-04-18 16:41:04 -07003488 IPCThreadState* ipc = IPCThreadState::self();
3489 const int pid = ipc->getCallingPid();
3490 const int uid = ipc->getCallingUid();
3491 if ((uid != AID_SHELL) &&
3492 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003493 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003494 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003495 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003496 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003497 // (this would indicate SF is stuck, but we want to be able to
3498 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003499 status_t err = mStateLock.timedLock(s2ns(1));
3500 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003501 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003502 result.appendFormat(
3503 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3504 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003505 }
3506
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003507 bool dumpAll = true;
3508 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003509 size_t numArgs = args.size();
3510 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003511 if ((index < numArgs) &&
3512 (args[index] == String16("--list"))) {
3513 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003514 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003515 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003516 }
3517
3518 if ((index < numArgs) &&
3519 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003520 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003521 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003522 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003523 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003524
3525 if ((index < numArgs) &&
3526 (args[index] == String16("--latency-clear"))) {
3527 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003528 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003529 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003530 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003531
3532 if ((index < numArgs) &&
3533 (args[index] == String16("--dispsync"))) {
3534 index++;
3535 mPrimaryDispSync.dump(result);
3536 dumpAll = false;
3537 }
Dan Stozab90cf072015-03-05 11:05:59 -08003538
3539 if ((index < numArgs) &&
3540 (args[index] == String16("--static-screen"))) {
3541 index++;
3542 dumpStaticScreenStats(result);
3543 dumpAll = false;
3544 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003545
3546 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003547 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003548 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003549 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003550 dumpAll = false;
3551 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003552
3553 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3554 index++;
3555 dumpWideColorInfo(result);
3556 dumpAll = false;
3557 }
chaviw1d044282017-09-27 12:19:28 -07003558
3559 if ((index < numArgs) && (args[index] == String16("--proto"))) {
3560 index++;
3561 LayersProto layersProto = dumpProtoInfo();
3562 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3563 dumpAll = false;
3564 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003565 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003566
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003567 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003568 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003569 }
3570
Mathias Agopian9795c422009-08-26 16:36:26 -07003571 if (locked) {
3572 mStateLock.unlock();
3573 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574 }
3575 write(fd, result.string(), result.size());
3576 return NO_ERROR;
3577}
3578
Dan Stozac7014012014-02-14 15:03:43 -08003579void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3580 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003581{
Robert Carr2047fae2016-11-28 14:09:09 -08003582 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003583 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003584 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003585}
3586
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003587void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003588 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003589{
3590 String8 name;
3591 if (index < args.size()) {
3592 name = String8(args[index]);
3593 index++;
3594 }
3595
Dan Stoza9e56aa02015-11-02 13:00:03 -08003596 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3597 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003598 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003599
3600 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003601 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003602 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003603 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003604 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003605 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003606 }
Robert Carr2047fae2016-11-28 14:09:09 -08003607 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003608 }
3609}
3610
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003611void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003612 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003613{
3614 String8 name;
3615 if (index < args.size()) {
3616 name = String8(args[index]);
3617 index++;
3618 }
3619
Robert Carr2047fae2016-11-28 14:09:09 -08003620 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003621 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003622 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003623 }
Robert Carr2047fae2016-11-28 14:09:09 -08003624 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003625
Svetoslavd85084b2014-03-20 10:28:31 -07003626 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003627}
3628
Jamie Gennis6547ff42013-07-16 20:12:42 -07003629// This should only be called from the main thread. Otherwise it would need
3630// the lock and should use mCurrentState rather than mDrawingState.
3631void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003632 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003633 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003634 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003635
3636 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3637}
3638
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003639void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003640{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003641 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003642 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3643
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003644 if (isLayerTripleBufferingDisabled())
3645 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003646
3647 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003648 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003649 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003650 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003651 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3652 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003653 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003654}
3655
Dan Stozab90cf072015-03-05 11:05:59 -08003656void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3657{
3658 result.appendFormat("Static screen stats:\n");
3659 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3660 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3661 float percent = 100.0f *
3662 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3663 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3664 b + 1, bucketTimeSec, percent);
3665 }
3666 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3667 float percent = 100.0f *
3668 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3669 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3670 NUM_BUCKETS - 1, bucketTimeSec, percent);
3671}
3672
Dan Stozae77c7662016-05-13 11:37:28 -07003673void SurfaceFlinger::recordBufferingStats(const char* layerName,
3674 std::vector<OccupancyTracker::Segment>&& history) {
3675 Mutex::Autolock lock(mBufferingStatsMutex);
3676 auto& stats = mBufferingStats[layerName];
3677 for (const auto& segment : history) {
3678 if (!segment.usedThirdBuffer) {
3679 stats.twoBufferTime += segment.totalTime;
3680 }
3681 if (segment.occupancyAverage < 1.0f) {
3682 stats.doubleBufferedTime += segment.totalTime;
3683 } else if (segment.occupancyAverage < 2.0f) {
3684 stats.tripleBufferedTime += segment.totalTime;
3685 }
3686 ++stats.numSegments;
3687 stats.totalTime += segment.totalTime;
3688 }
3689}
3690
Brian Andersond6927fb2016-07-23 23:37:30 -07003691void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3692 result.appendFormat("Layer frame timestamps:\n");
3693
3694 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3695 const size_t count = currentLayers.size();
3696 for (size_t i=0 ; i<count ; i++) {
3697 currentLayers[i]->dumpFrameEvents(result);
3698 }
3699}
3700
Dan Stozae77c7662016-05-13 11:37:28 -07003701void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3702 result.append("Buffering stats:\n");
3703 result.append(" [Layer name] <Active time> <Two buffer> "
3704 "<Double buffered> <Triple buffered>\n");
3705 Mutex::Autolock lock(mBufferingStatsMutex);
3706 typedef std::tuple<std::string, float, float, float> BufferTuple;
3707 std::map<float, BufferTuple, std::greater<float>> sorted;
3708 for (const auto& statsPair : mBufferingStats) {
3709 const char* name = statsPair.first.c_str();
3710 const BufferingStats& stats = statsPair.second;
3711 if (stats.numSegments == 0) {
3712 continue;
3713 }
3714 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3715 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3716 stats.totalTime;
3717 float doubleBufferRatio = static_cast<float>(
3718 stats.doubleBufferedTime) / stats.totalTime;
3719 float tripleBufferRatio = static_cast<float>(
3720 stats.tripleBufferedTime) / stats.totalTime;
3721 sorted.insert({activeTime, {name, twoBufferRatio,
3722 doubleBufferRatio, tripleBufferRatio}});
3723 }
3724 for (const auto& sortedPair : sorted) {
3725 float activeTime = sortedPair.first;
3726 const BufferTuple& values = sortedPair.second;
3727 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3728 std::get<0>(values).c_str(), activeTime,
3729 std::get<1>(values), std::get<2>(values),
3730 std::get<3>(values));
3731 }
3732 result.append("\n");
3733}
3734
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003735void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3736 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003737 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003738
3739 // TODO: print out if wide-color mode is active or not
3740
3741 for (size_t d = 0; d < mDisplays.size(); d++) {
3742 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3743 int32_t hwcId = displayDevice->getHwcDisplayId();
3744 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3745 continue;
3746 }
3747
3748 result.appendFormat("Display %d color modes:\n", hwcId);
3749 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3750 for (auto&& mode : modes) {
3751 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3752 }
3753
3754 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3755 result.appendFormat(" Current color mode: %s (%d)\n",
3756 decodeColorMode(currentMode).c_str(), currentMode);
3757 }
3758 result.append("\n");
3759}
3760
chaviw1d044282017-09-27 12:19:28 -07003761LayersProto SurfaceFlinger::dumpProtoInfo() const {
3762 LayersProto layersProto;
3763 mCurrentState.traverseInZOrder([&](Layer* layer) {
3764 LayerProto* layerProto = layersProto.add_layers();
3765 layer->writeToProto(layerProto, LayerVector::StateSet::Current);
3766 });
3767
3768 return layersProto;
3769}
3770
Mathias Agopian74d211a2013-04-22 16:55:35 +02003771void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3772 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003773{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003774 bool colorize = false;
3775 if (index < args.size()
3776 && (args[index] == String16("--color"))) {
3777 colorize = true;
3778 index++;
3779 }
3780
3781 Colorizer colorizer(colorize);
3782
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003783 // figure out if we're stuck somewhere
3784 const nsecs_t now = systemTime();
3785 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3786 const nsecs_t inTransaction(mDebugInTransaction);
3787 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3788 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3789
3790 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003791 * Dump library configuration.
3792 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003793
3794 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003795 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003796 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003797 appendSfConfigString(result);
3798 appendUiConfigString(result);
3799 appendGuiConfigString(result);
3800 result.append("\n");
3801
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003802 result.append("\nWide-Color information:\n");
3803 dumpWideColorInfo(result);
3804
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003805 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003806 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003807 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003808 result.append(SyncFeatures::getInstance().toString());
3809 result.append("\n");
3810
Dan Stoza9e56aa02015-11-02 13:00:03 -08003811 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3812
Andy McFadden41d67d72014-04-25 16:58:34 -07003813 colorizer.bold(result);
3814 result.append("DispSync configuration: ");
3815 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003816 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003817 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003818 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003819 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003820 result.append("\n");
3821
Dan Stozab90cf072015-03-05 11:05:59 -08003822 // Dump static screen stats
3823 result.append("\n");
3824 dumpStaticScreenStats(result);
3825 result.append("\n");
3826
Dan Stozae77c7662016-05-13 11:37:28 -07003827 dumpBufferingStats(result);
3828
Andy McFadden4803b742012-09-24 19:07:20 -07003829 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003830 * Dump the visible layer list
3831 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003832 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003833 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003834 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003835
3836 LayersProto layersProto = dumpProtoInfo();
3837 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3838 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003839
3840 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003841 * Dump Display state
3842 */
3843
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003844 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003845 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003846 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003847 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3848 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003849 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003850 }
3851
3852 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003853 * Dump SurfaceFlinger global state
3854 */
3855
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003856 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003857 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003858 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003859
Mathias Agopian888c8222012-08-04 21:10:38 -07003860 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003861 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003862
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003863 colorizer.bold(result);
3864 result.appendFormat("EGL implementation : %s\n",
3865 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3866 colorizer.reset(result);
3867 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003868 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003869
Mathias Agopian875d8e12013-06-07 15:35:48 -07003870 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003871
Mathias Agopian42977342012-08-05 00:40:46 -07003872 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003873 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3874 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003875 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003876 " last eglSwapBuffers() time: %f us\n"
3877 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003878 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003879 " refresh-rate : %f fps\n"
3880 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003881 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003882 " gpu_to_cpu_unsupported : %d\n"
3883 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003884 mLastSwapBufferTime/1000.0,
3885 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003886 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003887 1e9 / activeConfig->getVsyncPeriod(),
3888 activeConfig->getDpiX(),
3889 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003890 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003891
Mathias Agopian74d211a2013-04-22 16:55:35 +02003892 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003893 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003894
Mathias Agopian74d211a2013-04-22 16:55:35 +02003895 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003896 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003897
3898 /*
3899 * VSYNC state
3900 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003901 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003902 result.append("\n");
3903
3904 /*
3905 * HWC layer minidump
3906 */
3907 for (size_t d = 0; d < mDisplays.size(); d++) {
3908 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3909 int32_t hwcId = displayDevice->getHwcDisplayId();
3910 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3911 continue;
3912 }
3913
3914 result.appendFormat("Display %d HWC layers:\n", hwcId);
3915 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003916 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003917 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003918 });
Dan Stozae22aec72016-08-01 13:20:59 -07003919 result.append("\n");
3920 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003921
3922 /*
3923 * Dump HWComposer state
3924 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003925 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003926 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003927 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003928 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003929 result.appendFormat(" h/w composer %s\n",
3930 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003931 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003932
3933 /*
3934 * Dump gralloc state
3935 */
3936 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3937 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003938
3939 /*
3940 * Dump VrFlinger state if in use.
3941 */
3942 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3943 result.append("VrFlinger state:\n");
3944 result.append(mVrFlinger->Dump().c_str());
3945 result.append("\n");
3946 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003947}
3948
Mathias Agopian13127d82013-03-05 17:47:11 -08003949const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003950SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003951 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003952 wp<IBinder> dpy;
3953 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3954 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3955 dpy = mDisplays.keyAt(i);
3956 break;
3957 }
3958 }
3959 if (dpy == NULL) {
3960 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3961 // Just use the primary display so we have something to return
3962 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3963 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003964 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003965}
3966
Keun young Park63f165f2012-08-31 10:53:36 -07003967bool SurfaceFlinger::startDdmConnection()
3968{
3969 void* libddmconnection_dso =
3970 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3971 if (!libddmconnection_dso) {
3972 return false;
3973 }
3974 void (*DdmConnection_start)(const char* name);
3975 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003976 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003977 if (!DdmConnection_start) {
3978 dlclose(libddmconnection_dso);
3979 return false;
3980 }
3981 (*DdmConnection_start)(getServiceName());
3982 return true;
3983}
3984
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003985status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003986 switch (code) {
3987 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003988 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003989 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003990 case CLEAR_ANIMATION_FRAME_STATS:
3991 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003992 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003993 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07003994 case ENABLE_VSYNC_INJECTIONS:
3995 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003996 {
3997 // codes that require permission check
3998 IPCThreadState* ipc = IPCThreadState::self();
3999 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004000 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004001 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004002 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004003 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004004 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004005 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004006 break;
4007 }
Robert Carr1db73f62016-12-21 12:58:51 -08004008 /*
4009 * Calling setTransactionState is safe, because you need to have been
4010 * granted a reference to Client* and Handle* to do anything with it.
4011 *
4012 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4013 */
4014 case SET_TRANSACTION_STATE:
4015 case CREATE_SCOPED_CONNECTION:
4016 {
4017 return OK;
4018 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004019 case CAPTURE_SCREEN:
4020 {
4021 // codes that require permission check
4022 IPCThreadState* ipc = IPCThreadState::self();
4023 const int pid = ipc->getCallingPid();
4024 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004025 if ((uid != AID_GRAPHICS) &&
4026 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004027 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004028 return PERMISSION_DENIED;
4029 }
4030 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004031 }
4032 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004033 return OK;
4034}
4035
4036status_t SurfaceFlinger::onTransact(
4037 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4038{
4039 status_t credentialCheck = CheckTransactCodeCredentials(code);
4040 if (credentialCheck != OK) {
4041 return credentialCheck;
4042 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004043
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004044 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4045 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004046 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004047 IPCThreadState* ipc = IPCThreadState::self();
4048 const int uid = ipc->getCallingUid();
4049 if (CC_UNLIKELY(uid != AID_SYSTEM
4050 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004051 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004052 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004053 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004054 return PERMISSION_DENIED;
4055 }
4056 int n;
4057 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004058 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004059 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004060 return NO_ERROR;
4061 case 1002: // SHOW_UPDATES
4062 n = data.readInt32();
4063 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004064 invalidateHwcGeometry();
4065 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004066 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004067 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004068 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004069 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004070 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004071 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004072 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004073 setTransactionFlags(
4074 eTransactionNeeded|
4075 eDisplayTransactionNeeded|
4076 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004077 return NO_ERROR;
4078 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004079 case 1006:{ // send empty update
4080 signalRefresh();
4081 return NO_ERROR;
4082 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004083 case 1008: // toggle use of hw composer
4084 n = data.readInt32();
4085 mDebugDisableHWC = n ? 1 : 0;
4086 invalidateHwcGeometry();
4087 repaintEverything();
4088 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004089 case 1009: // toggle use of transform hint
4090 n = data.readInt32();
4091 mDebugDisableTransformHint = n ? 1 : 0;
4092 invalidateHwcGeometry();
4093 repaintEverything();
4094 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004095 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004096 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004097 reply->writeInt32(0);
4098 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004099 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004100 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004101 return NO_ERROR;
4102 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004103 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004104 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004105 return NO_ERROR;
4106 }
4107 case 1014: {
4108 // daltonize
4109 n = data.readInt32();
4110 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004111 case 1:
4112 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4113 break;
4114 case 2:
4115 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4116 break;
4117 case 3:
4118 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4119 break;
4120 default:
4121 mDaltonizer.setType(ColorBlindnessType::None);
4122 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004123 }
4124 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004125 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004126 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004127 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004128 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004129 invalidateHwcGeometry();
4130 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004131 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004132 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004133 case 1015: {
4134 // apply a color matrix
4135 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004136 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004137 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004138 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004139 for (size_t j = 0; j < 4; j++) {
4140 mColorMatrix[i][j] = data.readFloat();
4141 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004142 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004143 } else {
4144 mColorMatrix = mat4();
4145 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004146
4147 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4148 // the division by w in the fragment shader
4149 float4 lastRow(transpose(mColorMatrix)[3]);
4150 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4151 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4152 }
4153
Alan Viverette9c5a3332013-09-12 20:04:35 -07004154 invalidateHwcGeometry();
4155 repaintEverything();
4156 return NO_ERROR;
4157 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004158 // This is an experimental interface
4159 // Needs to be shifted to proper binder interface when we productize
4160 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004161 n = data.readInt32();
4162 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004163 return NO_ERROR;
4164 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004165 case 1017: {
4166 n = data.readInt32();
4167 mForceFullDamage = static_cast<bool>(n);
4168 return NO_ERROR;
4169 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004170 case 1018: { // Modify Choreographer's phase offset
4171 n = data.readInt32();
4172 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4173 return NO_ERROR;
4174 }
4175 case 1019: { // Modify SurfaceFlinger's phase offset
4176 n = data.readInt32();
4177 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4178 return NO_ERROR;
4179 }
Irvel468051e2016-06-13 16:44:44 -07004180 case 1020: { // Layer updates interceptor
4181 n = data.readInt32();
4182 if (n) {
4183 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004184 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004185 }
4186 else{
4187 ALOGV("Interceptor disabled");
4188 mInterceptor.disable();
4189 }
4190 return NO_ERROR;
4191 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004192 case 1021: { // Disable HWC virtual displays
4193 n = data.readInt32();
4194 mUseHwcVirtualDisplays = !n;
4195 return NO_ERROR;
4196 }
Romain Guy0147a172017-06-01 13:53:56 -07004197 case 1022: { // Set saturation boost
4198 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4199
4200 invalidateHwcGeometry();
4201 repaintEverything();
4202 return NO_ERROR;
4203 }
Romain Guy54f154a2017-10-24 21:40:32 +01004204 case 1023: { // Set native mode
4205 mForceNativeColorMode = data.readInt32() == 1;
4206
4207 invalidateHwcGeometry();
4208 repaintEverything();
4209 return NO_ERROR;
4210 }
4211 case 1024: { // Is wide color gamut rendering/color management supported?
4212 reply->writeBool(hasWideColorDisplay);
4213 return NO_ERROR;
4214 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004215 }
4216 }
4217 return err;
4218}
4219
Steven Thomas6d8110b2017-08-31 18:24:21 -07004220void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004221 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004222 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004223}
4224
Steven Thomas6d8110b2017-08-31 18:24:21 -07004225void SurfaceFlinger::repaintEverything() {
4226 ConditionalLock _l(mStateLock,
4227 std::this_thread::get_id() != mMainThreadId);
4228 repaintEverythingLocked();
4229}
4230
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004231// Checks that the requested width and height are valid and updates them to the display dimensions
4232// if they are set to 0
4233static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4234 Transform::orientation_flags rotation,
4235 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4236 // get screen geometry
4237 uint32_t displayWidth = displayDevice->getWidth();
4238 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004239
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004240 if (rotation & Transform::ROT_90) {
4241 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004242 }
4243
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004244 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4245 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4246 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4247 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004248 }
4249
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004250 if (*requestedWidth == 0) {
4251 *requestedWidth = displayWidth;
4252 }
4253 if (*requestedHeight == 0) {
4254 *requestedHeight = displayHeight;
4255 }
4256
4257 return NO_ERROR;
4258}
4259
4260// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4261class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004262public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004263 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4264 ~WindowDisconnector() {
4265 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004266 }
4267
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004268private:
4269 ANativeWindow* mWindow;
4270 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004271};
4272
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004273static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4274 uint32_t requestedHeight, bool hasWideColorDisplay,
4275 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4276 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4277 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4278
4279 int err = 0;
4280 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4281 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4282 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4283 err |= native_window_set_usage(window, usage);
4284
4285 if (hasWideColorDisplay) {
4286 err |= native_window_set_buffers_data_space(window,
4287 renderEngineUsesWideColor
4288 ? HAL_DATASPACE_DISPLAY_P3
4289 : HAL_DATASPACE_V0_SRGB);
4290 }
4291
4292 if (err != NO_ERROR) {
4293 return BAD_VALUE;
4294 }
4295
4296 /* TODO: Once we have the sync framework everywhere this can use
4297 * server-side waits on the fence that dequeueBuffer returns.
4298 */
4299 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4300 if (err != NO_ERROR) {
4301 return err;
4302 }
4303
4304 return NO_ERROR;
4305}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004306
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004307status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4308 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004309 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004310 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004311 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004312 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004313
4314 if (CC_UNLIKELY(display == 0))
4315 return BAD_VALUE;
4316
4317 if (CC_UNLIKELY(producer == 0))
4318 return BAD_VALUE;
4319
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004320 // if we have secure windows on this display, never allow the screen capture
4321 // unless the producer interface is local (i.e.: we can take a screenshot for
4322 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004323 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004324
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004325 // Convert to surfaceflinger's internal rotation type.
4326 Transform::orientation_flags rotationFlags;
4327 switch (rotation) {
4328 case ISurfaceComposer::eRotateNone:
4329 rotationFlags = Transform::ROT_0;
4330 break;
4331 case ISurfaceComposer::eRotate90:
4332 rotationFlags = Transform::ROT_90;
4333 break;
4334 case ISurfaceComposer::eRotate180:
4335 rotationFlags = Transform::ROT_180;
4336 break;
4337 case ISurfaceComposer::eRotate270:
4338 rotationFlags = Transform::ROT_270;
4339 break;
4340 default:
4341 rotationFlags = Transform::ROT_0;
4342 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4343 break;
4344 }
4345
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004346 { // Autolock scope
4347 Mutex::Autolock lock(mStateLock);
4348 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4349 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004350 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004351
4352 // create a surface (because we're a producer, and we need to
4353 // dequeue/queue a buffer)
4354 sp<Surface> surface = new Surface(producer, false);
4355
4356 // Put the screenshot Surface into async mode so that
4357 // Layer::headFenceHasSignaled will always return true and we'll latch the
4358 // first buffer regardless of whether or not its acquire fence has
4359 // signaled. This is needed to avoid a race condition in the rotation
4360 // animation. See b/30209608
4361 surface->setAsyncMode(true);
4362
4363 ANativeWindow* window = surface.get();
4364
4365 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4366 if (result != NO_ERROR) {
4367 return result;
4368 }
4369 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4370
4371 ANativeWindowBuffer* buffer = nullptr;
Romain Guy54f154a2017-10-24 21:40:32 +01004372 result = getWindowBuffer(window, reqWidth, reqHeight,
4373 hasWideColorDisplay && !mForceNativeColorMode,
4374 getRenderEngine().usesWideColor(), &buffer);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004375 if (result != NO_ERROR) {
4376 return result;
4377 }
4378
4379 // This mutex protects syncFd and captureResult for communication of the return values from the
4380 // main thread back to this Binder thread
4381 std::mutex captureMutex;
4382 std::condition_variable captureCondition;
4383 std::unique_lock<std::mutex> captureLock(captureMutex);
4384 int syncFd = -1;
4385 std::optional<status_t> captureResult;
4386
4387 sp<LambdaMessage> message = new LambdaMessage([&]() {
4388 // If there is a refresh pending, bug out early and tell the binder thread to try again
4389 // after the refresh.
4390 if (mRefreshPending) {
4391 ATRACE_NAME("Skipping screenshot for now");
4392 std::unique_lock<std::mutex> captureLock(captureMutex);
4393 captureResult = std::make_optional<status_t>(EAGAIN);
4394 captureCondition.notify_one();
4395 return;
4396 }
4397
4398 status_t result = NO_ERROR;
4399 int fd = -1;
4400 {
4401 Mutex::Autolock _l(mStateLock);
4402 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4403 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4404 minLayerZ, maxLayerZ, useIdentityTransform,
4405 rotationFlags, isLocalScreenshot, &fd);
4406 }
4407
4408 {
4409 std::unique_lock<std::mutex> captureLock(captureMutex);
4410 syncFd = fd;
4411 captureResult = std::make_optional<status_t>(result);
4412 captureCondition.notify_one();
4413 }
4414 });
4415
4416 result = postMessageAsync(message);
4417 if (result == NO_ERROR) {
4418 captureCondition.wait(captureLock, [&]() { return captureResult; });
4419 while (*captureResult == EAGAIN) {
4420 captureResult.reset();
4421 result = postMessageAsync(message);
4422 if (result != NO_ERROR) {
4423 return result;
4424 }
4425 captureCondition.wait(captureLock, [&]() { return captureResult; });
4426 }
4427 result = *captureResult;
4428 }
4429
4430 if (result == NO_ERROR) {
4431 // queueBuffer takes ownership of syncFd
4432 result = window->queueBuffer(window, buffer, syncFd);
4433 }
4434
4435 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004436}
4437
Mathias Agopian180f10d2013-04-10 22:55:41 -07004438
4439void SurfaceFlinger::renderScreenImplLocked(
4440 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004441 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004442 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004443 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004444{
4445 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004446 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004447
4448 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004449 const int32_t hw_w = hw->getWidth();
4450 const int32_t hw_h = hw->getHeight();
4451 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004452 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004453
Dan Stozac1879002014-05-22 15:59:05 -07004454 // if a default or invalid sourceCrop is passed in, set reasonable values
4455 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4456 !sourceCrop.isValid()) {
4457 sourceCrop.setLeftTop(Point(0, 0));
4458 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4459 }
4460
4461 // ensure that sourceCrop is inside screen
4462 if (sourceCrop.left < 0) {
4463 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4464 }
Dan Stozabe31f442014-06-11 11:20:54 -07004465 if (sourceCrop.right > hw_w) {
4466 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004467 }
4468 if (sourceCrop.top < 0) {
4469 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4470 }
Dan Stozabe31f442014-06-11 11:20:54 -07004471 if (sourceCrop.bottom > hw_h) {
4472 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004473 }
4474
Romain Guy88d37dd2017-05-26 17:57:05 -07004475#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01004476 engine.setWideColor(hw->getWideColorSupport() && !mForceNativeColorMode);
4477 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE : hw->getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004478#endif
4479
Mathias Agopian180f10d2013-04-10 22:55:41 -07004480 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004481 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004482
4483 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004484 engine.setViewportAndProjection(
4485 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004486 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004487
4488 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004489 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004490
Robert Carr1f0a16a2016-10-24 16:27:39 -07004491 // We loop through the first level of layers without traversing,
4492 // as we need to interpret min/max layer Z in the top level Z space.
4493 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004494 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004495 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004496 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004497 const Layer::State& state(layer->getDrawingState());
4498 if (state.z < minLayerZ || state.z > maxLayerZ) {
4499 continue;
4500 }
Dan Stoza412903f2017-04-27 13:42:17 -07004501 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004502 if (!layer->isVisible()) {
4503 return;
4504 }
4505 if (filtering) layer->setFiltering(true);
4506 layer->draw(hw, useIdentityTransform);
4507 if (filtering) layer->setFiltering(false);
4508 });
4509 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004510
Mathias Agopian931bda12013-08-28 18:11:46 -07004511 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004512}
4513
Dan Stozaabcda352017-06-01 14:37:39 -07004514// A simple RAII class that holds an EGLImage and destroys it either:
4515// a) When the destroy() method is called
4516// b) When the object goes out of scope
4517class ImageHolder {
4518public:
4519 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4520 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004521
Dan Stozaabcda352017-06-01 14:37:39 -07004522 void destroy() {
4523 if (mImage != EGL_NO_IMAGE_KHR) {
4524 eglDestroyImageKHR(mDisplay, mImage);
4525 mImage = EGL_NO_IMAGE_KHR;
4526 }
4527 }
4528
4529private:
4530 const EGLDisplay mDisplay;
4531 EGLImageKHR mImage;
4532};
4533
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004534status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4535 ANativeWindowBuffer* buffer, Rect sourceCrop,
4536 uint32_t reqWidth, uint32_t reqHeight,
4537 int32_t minLayerZ, int32_t maxLayerZ,
4538 bool useIdentityTransform,
4539 Transform::orientation_flags rotation,
4540 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004541 ATRACE_CALL();
4542
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004543 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004544 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004545 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004546 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004547 (state.z < minLayerZ || state.z > maxLayerZ)) {
4548 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004549 }
Dan Stoza412903f2017-04-27 13:42:17 -07004550 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004551 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4552 layer->isSecure());
4553 });
4554 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004555
4556 if (!isLocalScreenshot && secureLayerIsVisible) {
4557 ALOGW("FB is protected: PERMISSION_DENIED");
4558 return PERMISSION_DENIED;
4559 }
4560
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004561 int syncFd = -1;
4562 // create an EGLImage from the buffer so we can later
4563 // turn it into a texture
4564 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4565 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4566 if (image == EGL_NO_IMAGE_KHR) {
4567 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004568 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004569
Dan Stozaabcda352017-06-01 14:37:39 -07004570 // This will automatically destroy the image if we return before calling its destroy method
4571 ImageHolder imageHolder(mEGLDisplay, image);
4572
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004573 // this binds the given EGLImage as a framebuffer for the
4574 // duration of this scope.
4575 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004576 if (imageBond.getStatus() != NO_ERROR) {
4577 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004578 return INVALID_OPERATION;
4579 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004580
Dan Stozaabcda352017-06-01 14:37:39 -07004581 // this will in fact render into our dequeued buffer
4582 // via an FBO, which means we didn't have to create
4583 // an EGLSurface and therefore we're not
4584 // dependent on the context's EGLConfig.
4585 renderScreenImplLocked(
4586 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4587 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004588
Dan Stozaabcda352017-06-01 14:37:39 -07004589 // Attempt to create a sync khr object that can produce a sync point. If that
4590 // isn't available, create a non-dupable sync object in the fallback path and
4591 // wait on it directly.
4592 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4593 if (!DEBUG_SCREENSHOTS) {
4594 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4595 // native fence fd will not be populated until flush() is done.
4596 getRenderEngine().flush();
4597 }
4598
4599 if (sync != EGL_NO_SYNC_KHR) {
4600 // get the sync fd
4601 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4602 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4603 ALOGW("captureScreen: failed to dup sync khr object");
4604 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004605 }
Dan Stozaabcda352017-06-01 14:37:39 -07004606 eglDestroySyncKHR(mEGLDisplay, sync);
4607 } else {
4608 // fallback path
4609 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004610 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004611 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4612 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4613 EGLint eglErr = eglGetError();
4614 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4615 ALOGW("captureScreen: fence wait timed out");
4616 } else {
4617 ALOGW_IF(eglErr != EGL_SUCCESS,
4618 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004619 }
4620 eglDestroySyncKHR(mEGLDisplay, sync);
4621 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004622 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004623 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004624 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004625 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004626
4627 if (DEBUG_SCREENSHOTS) {
4628 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4629 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4630 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4631 hw, minLayerZ, maxLayerZ);
4632 delete [] pixels;
4633 }
4634
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004635 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004636 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004637
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004638 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004639}
4640
Mathias Agopiand5556842013-09-19 17:08:37 -07004641void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004642 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004643 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004644 for (size_t y=0 ; y<h ; y++) {
4645 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4646 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004647 if (p[x] != 0xFF000000) return;
4648 }
4649 }
4650 ALOGE("*** we just took a black screenshot ***\n"
4651 "requested minz=%d, maxz=%d, layerStack=%d",
4652 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004653
Robert Carr2047fae2016-11-28 14:09:09 -08004654 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004655 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004656 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004657 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004658 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004659 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004660 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4661 layer->isVisible() ? '+' : '-',
4662 i, layer->getName().string(), layer->getLayerStack(), state.z,
chaviw13fdc492017-06-27 12:40:18 -07004663 layer->isVisible(), state.flags, static_cast<float>(state.color.a));
Robert Carr1f0a16a2016-10-24 16:27:39 -07004664 i++;
4665 });
4666 }
4667 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004668 }
4669}
4670
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004671// ---------------------------------------------------------------------------
4672
Dan Stoza412903f2017-04-27 13:42:17 -07004673void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4674 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004675}
4676
Dan Stoza412903f2017-04-27 13:42:17 -07004677void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4678 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004679}
4680
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004681}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004682
4683
4684#if defined(__gl_h_)
4685#error "don't include gl/gl.h in this file"
4686#endif
4687
4688#if defined(__gl2_h_)
4689#error "don't include gl2/gl2.h in this file"
4690#endif