blob: 4154d6a87fbfea29af17ffbc0da8fbdd3ddd39fa [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
31#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080040#include <dvr/vr_flinger.h>
41
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060042#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070044#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070045
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080049#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080050#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051
52#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080055
Mathias Agopiancde87a32012-09-13 14:09:01 -070056#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/String8.h>
58#include <utils/String16.h>
59#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070060#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian921e6ac2012-07-23 23:11:29 -070063#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070064#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070070#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Mathias Agopiana4912602012-07-12 14:25:33 -070080#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070081#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070082#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
85
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070088
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090090#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092#define DISPLAY_COUNT 1
93
Mathias Agopianfee2b462013-07-03 12:34:01 -070094/*
95 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
96 * black pixels.
97 */
98#define DEBUG_SCREENSHOTS false
99
Mathias Agopianca088332013-03-28 17:44:13 -0700100EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700103
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108// ---------------------------------------------------------------------------
109
Mathias Agopian99b49842011-06-27 16:05:52 -0700110const String16 sHardwareTest("android.permission.HARDWARE_TEST");
111const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
112const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
113const String16 sDump("android.permission.DUMP");
114
115// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800116int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
117int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700118bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700119int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700120bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800121uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800122bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800123bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800124int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600125bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700126
Kalle Raitaa099a242017-01-11 11:17:29 -0800127
128std::string getHwcServiceName() {
129 char value[PROPERTY_VALUE_MAX] = {};
130 property_get("debug.sf.hwc_service_name", value, "default");
131 ALOGI("Using HWComposer service: '%s'", value);
132 return std::string(value);
133}
134
135bool useTrebleTestingOverride() {
136 char value[PROPERTY_VALUE_MAX] = {};
137 property_get("debug.sf.treble_testing_override", value, "false");
138 ALOGI("Treble testing override: '%s'", value);
139 return std::string(value) == "true";
140}
141
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700143 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800144 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700145 mTransactionPending(false),
146 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700147 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700148 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700149 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800150 mHwc(nullptr),
151 mRealHwc(nullptr),
152 mVrHwc(nullptr),
Kalle Raitaa099a242017-01-11 11:17:29 -0800153 mHwcServiceName(getHwcServiceName()),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800154 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800156 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800158 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800159 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700161 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700162 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700163 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700164 mDebugInSwapBuffers(0),
165 mLastSwapBufferTime(0),
166 mDebugInTransaction(0),
167 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700168 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700169 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800170 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000171 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700172 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700173 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700174 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800175 mHasPoweredOff(false),
176 mFrameBuckets(),
177 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700178 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800179 mNumLayers(0),
180 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800181{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800182 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800183
184 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
185 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
186
187 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
188 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
189
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800190 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
191 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700193 useContextPriority = getBool< ISurfaceFlingerConfigs,
194 &ISurfaceFlingerConfigs::useContextPriority>(false);
195
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700196 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
197 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
198
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700199 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
200 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
201
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800202 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
203 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
204
Steven Thomas050b2c82017-03-06 11:45:16 -0800205 // Vr flinger is only enabled on Daydream ready devices.
206 useVrFlinger = getBool< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::useVrFlinger>(false);
208
Fabien Sanglard1971b632017-03-10 14:50:03 -0800209 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
210 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
211
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600212 hasWideColorDisplay =
213 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
214
Saurabh Shahf4174532017-07-13 10:45:07 -0700215 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
216
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217 // debugging stuff...
218 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700219
Mathias Agopianb4b17302013-03-20 18:36:41 -0700220 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700221 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700222
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 property_get("debug.sf.showupdates", value, "0");
224 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700225
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700226 property_get("debug.sf.ddms", value, "0");
227 mDebugDDMS = atoi(value);
228 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700229 if (!startDdmConnection()) {
230 // start failed, and DDMS debugging not enabled
231 mDebugDDMS = 0;
232 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700233 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700234 ALOGI_IF(mDebugRegion, "showupdates enabled");
235 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700236
237 property_get("debug.sf.disable_backpressure", value, "0");
238 mPropagateBackpressure = !atoi(value);
239 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700240
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800241 property_get("debug.sf.enable_hwc_vds", value, "0");
242 mUseHwcVirtualDisplays = atoi(value);
243 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800244
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800245 property_get("ro.sf.disable_triple_buffer", value, "1");
246 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800247 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700248
Romain Guy11d63f42017-07-20 12:47:14 -0700249 // We should be reading 'persist.sys.sf.color_saturation' here
250 // but since /data may be encrypted, we need to wait until after vold
251 // comes online to attempt to read the property. The property is
252 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800253
254 if (useTrebleTestingOverride()) {
255 // Without the override SurfaceFlinger cannot connect to HIDL
256 // services that are not listed in the manifests. Considered
257 // deriving the setting from the set service name, but it
258 // would be brittle if the name that's not 'default' is used
259 // for production purposes later on.
260 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
261 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800262}
263
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800264void SurfaceFlinger::onFirstRef()
265{
266 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800267}
268
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800269SurfaceFlinger::~SurfaceFlinger()
270{
Mathias Agopiana4912602012-07-12 14:25:33 -0700271 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
272 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
273 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800274}
275
Dan Stozac7014012014-02-14 15:03:43 -0800276void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800277{
278 // the window manager died on us. prepare its eulogy.
279
Andy McFadden13a082e2012-08-24 10:16:42 -0700280 // restore initial conditions (default device unblank, etc)
281 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800282
283 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700284 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800285}
286
Robert Carr1db73f62016-12-21 12:58:51 -0800287static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700288 status_t err = client->initCheck();
289 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800290 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291 }
Robert Carr1db73f62016-12-21 12:58:51 -0800292 return nullptr;
293}
294
295sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
296 return initClient(new Client(this));
297}
298
299sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
300 const sp<IGraphicBufferProducer>& gbp) {
301 if (authenticateSurfaceTexture(gbp) == false) {
302 return nullptr;
303 }
304 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
305 if (layer == nullptr) {
306 return nullptr;
307 }
308
309 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800310}
311
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700312sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
313 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700314{
315 class DisplayToken : public BBinder {
316 sp<SurfaceFlinger> flinger;
317 virtual ~DisplayToken() {
318 // no more references, this display must be terminated
319 Mutex::Autolock _l(flinger->mStateLock);
320 flinger->mCurrentState.displays.removeItem(this);
321 flinger->setTransactionFlags(eDisplayTransactionNeeded);
322 }
323 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700324 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700325 : flinger(flinger) {
326 }
327 };
328
329 sp<BBinder> token = new DisplayToken(this);
330
331 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700332 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700333 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700334 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700335 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700336 return token;
337}
338
Jesse Hall6c913be2013-08-08 12:15:49 -0700339void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
340 Mutex::Autolock _l(mStateLock);
341
342 ssize_t idx = mCurrentState.displays.indexOfKey(display);
343 if (idx < 0) {
344 ALOGW("destroyDisplay: invalid display token");
345 return;
346 }
347
348 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
349 if (!info.isVirtualDisplay()) {
350 ALOGE("destroyDisplay called for non-virtual display");
351 return;
352 }
Irvelffc9efc2016-07-27 15:16:37 -0700353 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700354 mCurrentState.displays.removeItemsAt(idx);
355 setTransactionFlags(eDisplayTransactionNeeded);
356}
357
Jesse Hall692c7232012-11-08 15:41:56 -0800358void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800359 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800360 ALOGW_IF(mBuiltinDisplays[type],
361 "Overwriting display token for display type %d", type);
362 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800363 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700364 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800365 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700366 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800367}
368
Mathias Agopiane57f2922012-08-09 16:29:12 -0700369sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700370 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700371 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
372 return NULL;
373 }
Jesse Hall692c7232012-11-08 15:41:56 -0800374 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700375}
376
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800377void SurfaceFlinger::bootFinished()
378{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700379 if (mStartPropertySetThread->join() != NO_ERROR) {
380 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800381 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382 const nsecs_t now = systemTime();
383 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000384 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700385
386 // wait patiently for the window manager death
387 const String16 name("window");
388 sp<IBinder> window(defaultServiceManager()->getService(name));
389 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700390 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700391 }
392
Steven Thomas050b2c82017-03-06 11:45:16 -0800393 if (mVrFlinger) {
394 mVrFlinger->OnBootFinished();
395 }
396
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700397 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700398 // formerly we would just kill the process, but we now ask it to exit so it
399 // can choose where to stop the animation.
400 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700401
402 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
403 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
404 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700405
Romain Guyc53d3552017-07-20 18:49:46 -0700406 sp<LambdaMessage> bootFinished = new LambdaMessage([&]() {
407 mBootFinished = true;
408
Romain Guy11d63f42017-07-20 12:47:14 -0700409 readPersistentProperties();
Romain Guyc53d3552017-07-20 18:49:46 -0700410
411#ifdef USE_HWC2
412 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
413 if (hw->getWideColorSupport()) {
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -0600414 hw->setCompositionDataSpace(HAL_DATASPACE_V0_SRGB);
Romain Guyc53d3552017-07-20 18:49:46 -0700415 setActiveColorModeInternal(hw, HAL_COLOR_MODE_SRGB);
416 }
417#endif
Romain Guy11d63f42017-07-20 12:47:14 -0700418 });
Romain Guyc53d3552017-07-20 18:49:46 -0700419 postMessageAsync(bootFinished);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800420}
421
Mathias Agopian3f844832013-08-07 21:24:32 -0700422void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700423 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700424 RenderEngine& engine;
425 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700426 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700427 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
428 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700429 }
430 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700431 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700432 return true;
433 }
434 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700435 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700436}
437
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438class DispSyncSource : public VSyncSource, private DispSync::Callback {
439public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700440 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000441 const char* name) :
442 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700443 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700444 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000445 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
446 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700447 mDispSync(dispSync),
448 mCallbackMutex(),
449 mCallback(),
450 mVsyncMutex(),
451 mPhaseOffset(phaseOffset),
452 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700453
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454 virtual ~DispSyncSource() {}
455
456 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700457 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000459 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700460 static_cast<DispSync::Callback*>(this));
461 if (err != NO_ERROR) {
462 ALOGE("error registering vsync callback: %s (%d)",
463 strerror(-err), err);
464 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700465 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700466 } else {
467 status_t err = mDispSync->removeEventListener(
468 static_cast<DispSync::Callback*>(this));
469 if (err != NO_ERROR) {
470 ALOGE("error unregistering vsync callback: %s (%d)",
471 strerror(-err), err);
472 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700473 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700475 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700476 }
477
478 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700479 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 mCallback = callback;
481 }
482
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700483 virtual void setPhaseOffset(nsecs_t phaseOffset) {
484 Mutex::Autolock lock(mVsyncMutex);
485
486 // Normalize phaseOffset to [0, period)
487 auto period = mDispSync->getPeriod();
488 phaseOffset %= period;
489 if (phaseOffset < 0) {
490 // If we're here, then phaseOffset is in (-period, 0). After this
491 // operation, it will be in (0, period)
492 phaseOffset += period;
493 }
494 mPhaseOffset = phaseOffset;
495
496 // If we're not enabled, we don't need to mess with the listeners
497 if (!mEnabled) {
498 return;
499 }
500
501 // Remove the listener with the old offset
502 status_t err = mDispSync->removeEventListener(
503 static_cast<DispSync::Callback*>(this));
504 if (err != NO_ERROR) {
505 ALOGE("error unregistering vsync callback: %s (%d)",
506 strerror(-err), err);
507 }
508
509 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000510 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511 static_cast<DispSync::Callback*>(this));
512 if (err != NO_ERROR) {
513 ALOGE("error registering vsync callback: %s (%d)",
514 strerror(-err), err);
515 }
516 }
517
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518private:
519 virtual void onDispSyncEvent(nsecs_t when) {
520 sp<VSyncSource::Callback> callback;
521 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700522 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523 callback = mCallback;
524
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700525 if (mTraceVsync) {
526 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700527 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700528 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700529 }
530
531 if (callback != NULL) {
532 callback->onVSyncEvent(when);
533 }
534 }
535
Tim Murray4a4e4a22016-04-19 16:29:23 +0000536 const char* const mName;
537
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700538 int mValue;
539
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700540 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700541 const String8 mVsyncOnLabel;
542 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700543
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700545
546 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700547 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700548
549 Mutex mVsyncMutex; // Protects the following
550 nsecs_t mPhaseOffset;
551 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552};
553
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700554class InjectVSyncSource : public VSyncSource {
555public:
556 InjectVSyncSource() {}
557
558 virtual ~InjectVSyncSource() {}
559
560 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
561 std::lock_guard<std::mutex> lock(mCallbackMutex);
562 mCallback = callback;
563 }
564
565 virtual void onInjectSyncEvent(nsecs_t when) {
566 std::lock_guard<std::mutex> lock(mCallbackMutex);
567 mCallback->onVSyncEvent(when);
568 }
569
570 virtual void setVSyncEnabled(bool) {}
571 virtual void setPhaseOffset(nsecs_t) {}
572
573private:
574 std::mutex mCallbackMutex; // Protects the following
575 sp<VSyncSource::Callback> mCallback;
576};
577
Wei Wangf9b05ee2017-07-19 20:59:39 -0700578// Do not call property_set on main thread which will be blocked by init
579// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700580void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700581 ALOGI( "SurfaceFlinger's main thread ready to run. "
582 "Initializing graphics H/W...");
583
Romain Guyc53d3552017-07-20 18:49:46 -0700584 ALOGI("Phase offset NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900585
Dan Stoza9e56aa02015-11-02 13:00:03 -0800586 { // Autolock scope
587 Mutex::Autolock _l(mStateLock);
588
589 // initialize EGL for the default display
590 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
591 eglInitialize(mEGLDisplay, NULL, NULL);
592
593 // start the EventThread
594 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
595 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700596 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800597 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
598 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700599 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800600 mEventQueue.setEventThread(mSFEventThread);
601
Tim Murray22752852017-05-04 13:38:49 -0700602 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700603 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700604 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700605 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
606 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
607 }
Tim Murray22752852017-05-04 13:38:49 -0700608 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
609 ALOGE("Couldn't set SCHED_FIFO for EventThread");
610 }
Tim Murray41a38532016-06-22 12:42:10 -0700611
Dan Stoza9e56aa02015-11-02 13:00:03 -0800612 // Get a RenderEngine for the given display / config (can't fail)
613 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700614 HAL_PIXEL_FORMAT_RGBA_8888,
615 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800616 }
617
618 // Drop the state lock while we initialize the hardware composer. We drop
619 // the lock because on creation, it will call back into SurfaceFlinger to
620 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800621 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
622 "Starting with vr flinger active is not currently supported.");
Kalle Raitaa099a242017-01-11 11:17:29 -0800623 mRealHwc = new HWComposer(mHwcServiceName);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800624 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800625 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
626
Jesse Hall692c7232012-11-08 15:41:56 -0800627 Mutex::Autolock _l(mStateLock);
628
Steven Thomas050b2c82017-03-06 11:45:16 -0800629 if (useVrFlinger) {
630 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700631 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800632 mVrFlingerRequestsDisplay = requestDisplay;
633 signalTransaction();
634 };
635 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
636 vrFlingerRequestDisplayCallback);
637 if (!mVrFlinger) {
638 ALOGE("Failed to start vrflinger");
639 }
640 }
641
Mathias Agopian875d8e12013-06-07 15:35:48 -0700642 // retrieve the EGL context that was selected/created
643 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700644
Mathias Agopianda27af92012-09-13 18:17:13 -0700645 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
646 "couldn't create EGLContext");
647
Dan Stoza9e56aa02015-11-02 13:00:03 -0800648 // make the GLContext current so that we can create textures when creating
649 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700650 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700651
Jamie Gennisd1700752013-10-14 12:22:52 -0700652 mEventControlThread = new EventControlThread(this);
653 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
654
Mathias Agopian92a979a2012-08-02 18:32:23 -0700655 // initialize our drawing state
656 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700657
Andy McFadden13a082e2012-08-24 10:16:42 -0700658 // set initial conditions (e.g. unblank default device)
659 initializeDisplays();
660
Dan Stoza4e637772016-07-28 13:31:51 -0700661 mRenderEngine->primeCache();
662
Wei Wangf9b05ee2017-07-19 20:59:39 -0700663 // Inform native graphics APIs whether the present timestamp is supported:
664 if (getHwComposer().hasCapability(
665 HWC2::Capability::PresentFenceIsNotReliable)) {
666 mStartPropertySetThread = new StartPropertySetThread(false);
667 } else {
668 mStartPropertySetThread = new StartPropertySetThread(true);
669 }
670
671 if (mStartPropertySetThread->Start() != NO_ERROR) {
672 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800673 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800674
Dan Stoza9e56aa02015-11-02 13:00:03 -0800675 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700676}
677
Romain Guy11d63f42017-07-20 12:47:14 -0700678void SurfaceFlinger::readPersistentProperties() {
679 char value[PROPERTY_VALUE_MAX];
680
681 property_get("persist.sys.sf.color_saturation", value, "1.0");
682 mSaturation = atof(value);
683 ALOGV("Saturation is set to %.2f", mSaturation);
684}
685
Mathias Agopiana67e4182012-06-19 17:26:12 -0700686void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800687 // Start boot animation service by setting a property mailbox
688 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700689 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800690 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700691 if (mStartPropertySetThread->join() != NO_ERROR) {
692 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800693 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700694}
695
Mathias Agopian875d8e12013-06-07 15:35:48 -0700696size_t SurfaceFlinger::getMaxTextureSize() const {
697 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700698}
699
Mathias Agopian875d8e12013-06-07 15:35:48 -0700700size_t SurfaceFlinger::getMaxViewportDims() const {
701 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700702}
703
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800704// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800705
Jamie Gennis582270d2011-08-17 18:19:00 -0700706bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800707 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800708 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800709 return authenticateSurfaceTextureLocked(bufferProducer);
710}
711
712bool SurfaceFlinger::authenticateSurfaceTextureLocked(
713 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800714 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700715 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800716}
717
Brian Anderson6b376712017-04-04 10:51:39 -0700718status_t SurfaceFlinger::getSupportedFrameTimestamps(
719 std::vector<FrameEvent>* outSupported) const {
720 *outSupported = {
721 FrameEvent::REQUESTED_PRESENT,
722 FrameEvent::ACQUIRE,
723 FrameEvent::LATCH,
724 FrameEvent::FIRST_REFRESH_START,
725 FrameEvent::LAST_REFRESH_START,
726 FrameEvent::GPU_COMPOSITION_DONE,
727 FrameEvent::DEQUEUE_READY,
728 FrameEvent::RELEASE,
729 };
730 if (!getHwComposer().hasCapability(
731 HWC2::Capability::PresentFenceIsNotReliable)) {
732 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
733 }
734 return NO_ERROR;
735}
736
Dan Stoza7f7da322014-05-02 15:26:25 -0700737status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
738 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700739 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700740 return BAD_VALUE;
741 }
742
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500743 if (!display.get())
744 return NAME_NOT_FOUND;
745
Jesse Hall692c7232012-11-08 15:41:56 -0800746 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700747 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800748 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700749 type = i;
750 break;
751 }
752 }
753
754 if (type < 0) {
755 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700756 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700757
Mathias Agopian8b736f12012-08-13 17:54:26 -0700758 // TODO: Not sure if display density should handled by SF any longer
759 class Density {
760 static int getDensityFromProperty(char const* propName) {
761 char property[PROPERTY_VALUE_MAX];
762 int density = 0;
763 if (property_get(propName, property, NULL) > 0) {
764 density = atoi(property);
765 }
766 return density;
767 }
768 public:
769 static int getEmuDensity() {
770 return getDensityFromProperty("qemu.sf.lcd_density"); }
771 static int getBuildDensity() {
772 return getDensityFromProperty("ro.sf.lcd_density"); }
773 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700774
Dan Stoza7f7da322014-05-02 15:26:25 -0700775 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700776
Dan Stoza9e56aa02015-11-02 13:00:03 -0800777 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700778 DisplayInfo info = DisplayInfo();
779
Dan Stoza9e56aa02015-11-02 13:00:03 -0800780 float xdpi = hwConfig->getDpiX();
781 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700782
783 if (type == DisplayDevice::DISPLAY_PRIMARY) {
784 // The density of the device is provided by a build property
785 float density = Density::getBuildDensity() / 160.0f;
786 if (density == 0) {
787 // the build doesn't provide a density -- this is wrong!
788 // use xdpi instead
789 ALOGE("ro.sf.lcd_density must be defined as a build property");
790 density = xdpi / 160.0f;
791 }
792 if (Density::getEmuDensity()) {
793 // if "qemu.sf.lcd_density" is specified, it overrides everything
794 xdpi = ydpi = density = Density::getEmuDensity();
795 density /= 160.0f;
796 }
797 info.density = density;
798
799 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000800 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
801 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700802 } else {
803 // TODO: where should this value come from?
804 static const int TV_DENSITY = 213;
805 info.density = TV_DENSITY / 160.0f;
806 info.orientation = 0;
807 }
808
Dan Stoza9e56aa02015-11-02 13:00:03 -0800809 info.w = hwConfig->getWidth();
810 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 info.xdpi = xdpi;
812 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800813 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900814 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815
Andy McFadden91b2ca82014-06-13 14:04:23 -0700816 // This is how far in advance a buffer must be queued for
817 // presentation at a given time. If you want a buffer to appear
818 // on the screen at time N, you must submit the buffer before
819 // (N - presentationDeadline).
820 //
821 // Normally it's one full refresh period (to give SF a chance to
822 // latch the buffer), but this can be reduced by configuring a
823 // DispSync offset. Any additional delays introduced by the hardware
824 // composer or panel must be accounted for here.
825 //
826 // We add an additional 1ms to allow for processing time and
827 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800829 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700830
831 // All non-virtual displays are currently considered secure.
832 info.secure = true;
833
Michael Wright28f24d02016-07-12 13:30:53 -0700834 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 }
836
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 return NO_ERROR;
838}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700839
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800840status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700841 DisplayStatInfo* stats) {
842 if (stats == NULL) {
843 return BAD_VALUE;
844 }
845
846 // FIXME for now we always return stats for the primary display
847 memset(stats, 0, sizeof(*stats));
848 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
849 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
850 return NO_ERROR;
851}
852
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700853int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800854 if (display == NULL) {
855 ALOGE("%s : display is NULL", __func__);
856 return BAD_VALUE;
857 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700858
859 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700860 if (device != NULL) {
861 return device->getActiveConfig();
862 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700863
Dan Stoza24a42e92015-03-09 10:04:11 -0700864 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700865}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700866
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700867void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
868 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
869 this);
870 int32_t type = hw->getDisplayType();
871 int currentMode = hw->getActiveConfig();
872
873 if (mode == currentMode) {
874 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
875 return;
876 }
877
878 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
879 ALOGW("Trying to set config for virtual display");
880 return;
881 }
882
883 hw->setActiveConfig(mode);
884 getHwComposer().setActiveConfig(type, mode);
885}
886
887status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
888 class MessageSetActiveConfig: public MessageBase {
889 SurfaceFlinger& mFlinger;
890 sp<IBinder> mDisplay;
891 int mMode;
892 public:
893 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
894 int mode) :
895 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
896 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700897 Vector<DisplayInfo> configs;
898 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700899 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700900 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700901 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700902 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700903 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700904 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
905 if (hw == NULL) {
906 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700907 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700908 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
909 ALOGW("Attempt to set active config = %d for virtual display",
910 mMode);
911 } else {
912 mFlinger.setActiveConfigInternal(hw, mMode);
913 }
914 return true;
915 }
916 };
917 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
918 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700919 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700920}
Michael Wright28f24d02016-07-12 13:30:53 -0700921status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
922 Vector<android_color_mode_t>* outColorModes) {
923 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
924 return BAD_VALUE;
925 }
926
927 if (!display.get()) {
928 return NAME_NOT_FOUND;
929 }
930
931 int32_t type = NAME_NOT_FOUND;
932 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
933 if (display == mBuiltinDisplays[i]) {
934 type = i;
935 break;
936 }
937 }
938
939 if (type < 0) {
940 return type;
941 }
942
943 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
944 outColorModes->clear();
945 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
946
947 return NO_ERROR;
948}
949
950android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700951 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700952 if (device != nullptr) {
953 return device->getActiveColorMode();
954 }
955 return static_cast<android_color_mode_t>(BAD_VALUE);
956}
957
958void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
959 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700960 int32_t type = hw->getDisplayType();
961 android_color_mode_t currentMode = hw->getActiveColorMode();
962
963 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700964 return;
965 }
966
967 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
968 ALOGW("Trying to set config for virtual display");
969 return;
970 }
971
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600972 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
973 hw->getDisplayType());
974
Michael Wright28f24d02016-07-12 13:30:53 -0700975 hw->setActiveColorMode(mode);
976 getHwComposer().setActiveColorMode(type, mode);
977}
978
979
980status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
981 android_color_mode_t colorMode) {
982 class MessageSetActiveColorMode: public MessageBase {
983 SurfaceFlinger& mFlinger;
984 sp<IBinder> mDisplay;
985 android_color_mode_t mMode;
986 public:
987 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
988 android_color_mode_t mode) :
989 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
990 virtual bool handler() {
991 Vector<android_color_mode_t> modes;
992 mFlinger.getDisplayColorModes(mDisplay, &modes);
993 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
994 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600995 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
996 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700997 return true;
998 }
999 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1000 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001001 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1002 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001003 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001004 ALOGW("Attempt to set active color mode %s %d for virtual display",
1005 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001006 } else {
1007 mFlinger.setActiveColorModeInternal(hw, mMode);
1008 }
1009 return true;
1010 }
1011 };
1012 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1013 postMessageSync(msg);
1014 return NO_ERROR;
1015}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001016
Svetoslavd85084b2014-03-20 10:28:31 -07001017status_t SurfaceFlinger::clearAnimationFrameStats() {
1018 Mutex::Autolock _l(mStateLock);
1019 mAnimFrameTracker.clearStats();
1020 return NO_ERROR;
1021}
1022
1023status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1024 Mutex::Autolock _l(mStateLock);
1025 mAnimFrameTracker.getStats(outStats);
1026 return NO_ERROR;
1027}
1028
Dan Stozac4f471e2016-03-24 09:31:08 -07001029status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1030 HdrCapabilities* outCapabilities) const {
1031 Mutex::Autolock _l(mStateLock);
1032
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001033 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001034 if (displayDevice == nullptr) {
1035 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1036 return BAD_VALUE;
1037 }
1038
1039 std::unique_ptr<HdrCapabilities> capabilities =
1040 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1041 if (capabilities) {
1042 std::swap(*outCapabilities, *capabilities);
1043 } else {
1044 return BAD_VALUE;
1045 }
1046
1047 return NO_ERROR;
1048}
1049
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001050status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1051 if (enable == mInjectVSyncs) {
1052 return NO_ERROR;
1053 }
1054
1055 if (enable) {
1056 mInjectVSyncs = enable;
1057 ALOGV("VSync Injections enabled");
1058 if (mVSyncInjector.get() == nullptr) {
1059 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001060 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001061 }
1062 mEventQueue.setEventThread(mInjectorEventThread);
1063 } else {
1064 mInjectVSyncs = enable;
1065 ALOGV("VSync Injections disabled");
1066 mEventQueue.setEventThread(mSFEventThread);
1067 mVSyncInjector.clear();
1068 }
1069 return NO_ERROR;
1070}
1071
1072status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1073 if (!mInjectVSyncs) {
1074 ALOGE("VSync Injections not enabled");
1075 return BAD_VALUE;
1076 }
1077 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1078 ALOGV("Injecting VSync inside SurfaceFlinger");
1079 mVSyncInjector->onInjectSyncEvent(when);
1080 }
1081 return NO_ERROR;
1082}
1083
Kalle Raitaa099a242017-01-11 11:17:29 -08001084status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1085 IPCThreadState* ipc = IPCThreadState::self();
1086 const int pid = ipc->getCallingPid();
1087 const int uid = ipc->getCallingUid();
1088 if ((uid != AID_SHELL) &&
1089 !PermissionCache::checkPermission(sDump, pid, uid)) {
1090 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1091 return PERMISSION_DENIED;
1092 }
1093
1094 // Try to acquire a lock for 1s, fail gracefully
1095 const status_t err = mStateLock.timedLock(s2ns(1));
1096 const bool locked = (err == NO_ERROR);
1097 if (!locked) {
1098 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1099 return TIMED_OUT;
1100 }
1101
1102 outLayers->clear();
1103 mCurrentState.traverseInZOrder([&](Layer* layer) {
1104 outLayers->push_back(layer->getLayerDebugInfo());
1105 });
1106
1107 mStateLock.unlock();
1108 return NO_ERROR;
1109}
1110
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001111// ----------------------------------------------------------------------------
1112
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001113sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1114 ISurfaceComposer::VsyncSource vsyncSource) {
1115 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1116 return mSFEventThread->createEventConnection();
1117 } else {
1118 return mEventThread->createEventConnection();
1119 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001120}
1121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001122// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001123
1124void SurfaceFlinger::waitForEvent() {
1125 mEventQueue.waitMessage();
1126}
1127
1128void SurfaceFlinger::signalTransaction() {
1129 mEventQueue.invalidate();
1130}
1131
1132void SurfaceFlinger::signalLayerUpdate() {
1133 mEventQueue.invalidate();
1134}
1135
1136void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001137 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001138 mEventQueue.refresh();
1139}
1140
1141status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001142 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001143 return mEventQueue.postMessage(msg, reltime);
1144}
1145
1146status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001147 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001148 status_t res = mEventQueue.postMessage(msg, reltime);
1149 if (res == NO_ERROR) {
1150 msg->wait();
1151 }
1152 return res;
1153}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001154
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001155void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001156 do {
1157 waitForEvent();
1158 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001159}
1160
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001161void SurfaceFlinger::enableHardwareVsync() {
1162 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001163 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001164 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001165 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1166 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001167 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001168 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001169}
1170
Jesse Hall948fe0c2013-10-14 12:56:09 -07001171void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001172 Mutex::Autolock _l(mHWVsyncLock);
1173
Jesse Hall948fe0c2013-10-14 12:56:09 -07001174 if (makeAvailable) {
1175 mHWVsyncAvailable = true;
1176 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001177 // Hardware vsync is not currently available, so abort the resync
1178 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001179 return;
1180 }
1181
Dan Stoza9e56aa02015-11-02 13:00:03 -08001182 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1183 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184
1185 mPrimaryDispSync.reset();
1186 mPrimaryDispSync.setPeriod(period);
1187
1188 if (!mPrimaryHWVsyncEnabled) {
1189 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001190 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1191 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001192 mPrimaryHWVsyncEnabled = true;
1193 }
1194}
1195
Jesse Hall948fe0c2013-10-14 12:56:09 -07001196void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001197 Mutex::Autolock _l(mHWVsyncLock);
1198 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001199 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1200 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001201 mPrimaryDispSync.endResync();
1202 mPrimaryHWVsyncEnabled = false;
1203 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001204 if (makeUnavailable) {
1205 mHWVsyncAvailable = false;
1206 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001207}
1208
Tim Murray4a4e4a22016-04-19 16:29:23 +00001209void SurfaceFlinger::resyncWithRateLimit() {
1210 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001211
1212 // No explicit locking is needed here since EventThread holds a lock while calling this method
1213 static nsecs_t sLastResyncAttempted = 0;
1214 const nsecs_t now = systemTime();
1215 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001216 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001217 }
Dan Stoza57164302017-05-08 14:03:54 -07001218 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001219}
1220
Steven Thomas3cfac282017-02-06 12:29:30 -08001221void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1222 nsecs_t timestamp) {
1223 Mutex::Autolock lock(mStateLock);
1224 // Ignore any vsyncs from the non-active hardware composer.
1225 if (composer != mHwc) {
1226 return;
1227 }
1228
Jamie Gennisd1700752013-10-14 12:22:52 -07001229 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001230
Jamie Gennisd1700752013-10-14 12:22:52 -07001231 { // Scope for the lock
1232 Mutex::Autolock _l(mHWVsyncLock);
1233 if (type == 0 && mPrimaryHWVsyncEnabled) {
1234 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001235 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001236 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001237
1238 if (needsHwVsync) {
1239 enableHardwareVsync();
1240 } else {
1241 disableHardwareVsync(false);
1242 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001243}
1244
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001245void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001246 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001247 *compositorTiming = mCompositorTiming;
1248}
1249
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001250void SurfaceFlinger::createDefaultDisplayDevice() {
1251 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1252 wp<IBinder> token = mBuiltinDisplays[type];
1253
1254 // All non-virtual displays are currently considered secure.
1255 const bool isSecure = true;
1256
1257 sp<IGraphicBufferProducer> producer;
1258 sp<IGraphicBufferConsumer> consumer;
1259 BufferQueue::createBufferQueue(&producer, &consumer);
1260
1261 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1262
1263 bool hasWideColorModes = false;
1264 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1265 for (android_color_mode_t colorMode : modes) {
1266 switch (colorMode) {
1267 case HAL_COLOR_MODE_DISPLAY_P3:
1268 case HAL_COLOR_MODE_ADOBE_RGB:
1269 case HAL_COLOR_MODE_DCI_P3:
1270 hasWideColorModes = true;
1271 break;
1272 default:
1273 break;
1274 }
1275 }
1276 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1277 token, fbs, producer, mRenderEngine->getEGLConfig(),
1278 hasWideColorModes && hasWideColorDisplay);
1279 mDisplays.add(token, hw);
Romain Guyc53d3552017-07-20 18:49:46 -07001280 setActiveColorModeInternal(hw, HAL_COLOR_MODE_NATIVE);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001281 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001282}
1283
1284void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001285 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001286
1287 if (composer->isUsingVrComposer()) {
1288 // We handle initializing the primary display device for the VR
1289 // window manager hwc explicitly at the time of transition.
1290 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1291 ALOGE("External displays are not supported by the vr hardware composer.");
1292 }
1293 return;
1294 }
1295
Dan Stoza9e56aa02015-11-02 13:00:03 -08001296 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1297 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001298 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1299 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001300 } else {
1301 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001302 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001303 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001304 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001305 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001306 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1307 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001308 }
1309 setTransactionFlags(eDisplayTransactionNeeded);
1310
Andy McFadden9e9689c2012-10-10 18:17:51 -07001311 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001312 }
Mathias Agopian86303202012-07-24 22:46:10 -07001313}
1314
Steven Thomas3cfac282017-02-06 12:29:30 -08001315void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1316 Mutex::Autolock lock(mStateLock);
1317 if (composer == mHwc) {
1318 repaintEverything();
1319 } else {
1320 // This isn't from our current hardware composer. If it's a callback
1321 // from the real composer, forward the refresh request to vr
1322 // flinger. Otherwise ignore it.
1323 if (!composer->isUsingVrComposer()) {
1324 mVrFlinger->OnHardwareComposerRefresh();
1325 }
1326 }
1327}
1328
Dan Stoza9e56aa02015-11-02 13:00:03 -08001329void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001331 getHwComposer().setVsyncEnabled(disp,
1332 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001333}
1334
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001335// Note: it is assumed the caller holds |mStateLock| when this is called
1336void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001337 disableHardwareVsync(true);
1338 clearHwcLayers(mDrawingState.layersSortedByZ);
1339 clearHwcLayers(mCurrentState.layersSortedByZ);
Steven Thomasf5a5f6e2017-07-17 13:59:23 -07001340 for (size_t disp = 0; disp < mDisplays.size(); ++disp) {
1341 clearHwcLayers(mDisplays[disp]->getVisibleLayersSortedByZ());
1342 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001343 // Clear the drawing state so that the logic inside of
1344 // handleTransactionLocked will fire. It will determine the delta between
1345 // mCurrentState and mDrawingState and re-apply all changes when we make the
1346 // transition.
1347 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001348 // Release virtual display hwcId during vr mode transition.
1349 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1350 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1351 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1352 displayDevice->disconnect(getHwComposer());
1353 }
1354 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001355 mDisplays.clear();
1356}
1357
Steven Thomas050b2c82017-03-06 11:45:16 -08001358void SurfaceFlinger::updateVrFlinger() {
1359 if (!mVrFlinger)
1360 return;
1361 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1362 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001363 return;
1364 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001365
Steven Thomas050b2c82017-03-06 11:45:16 -08001366 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001367 // Construct new HWComposer without holding any locks.
Kalle Raitaa099a242017-01-11 11:17:29 -08001368 mVrHwc = new HWComposer("vr");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001369
1370 // Set up the event handlers. This step is neccessary to initialize the internal state of
1371 // the hardware composer object properly. Our callbacks are designed such that if they are
1372 // triggered between now and the point where the display is properly re-initialized, they
1373 // will not have any effect, so this is safe to do here, before the lock is aquired.
1374 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001375 ALOGV("Vr HWC created");
1376 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001377
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001378 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001379
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001380 if (vrFlingerRequestsDisplay) {
1381 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001383 mHwc = mVrHwc;
1384 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001385
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001386 } else {
1387 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001388
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001389 resetHwcLocked();
1390
1391 mHwc = mRealHwc;
1392 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001393 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001394
1395 mVisibleRegionsDirty = true;
1396 invalidateHwcGeometry();
1397
1398 // Explicitly re-initialize the primary display. This is because some other
1399 // parts of this class rely on the primary display always being available.
1400 createDefaultDisplayDevice();
1401
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001402 // Re-enable default display.
1403 sp<LambdaMessage> requestMessage = new LambdaMessage([&]() {
1404 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1405 setPowerModeInternal(hw, HWC_POWER_MODE_NORMAL);
1406
1407 // Reset the timing values to account for the period of the swapped in HWC
1408 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1409 const nsecs_t period = activeConfig->getVsyncPeriod();
1410 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1411
1412 // Use phase of 0 since phase is not known.
1413 // Use latency of 0, which will snap to the ideal latency.
1414 setCompositorTimingSnapped(0, period, 0);
1415 });
1416 postMessageAsync(requestMessage);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001417
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418 android_atomic_or(1, &mRepaintEverything);
1419 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001420}
1421
Mathias Agopian4fec8732012-06-29 14:12:52 -07001422void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001423 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001424 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001425 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001426 bool frameMissed = !mHadClientComposition &&
1427 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001428 (mPreviousPresentFence->getSignalTime() ==
1429 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001430 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001431 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001432 signalLayerUpdate();
1433 break;
1434 }
1435
Steven Thomas050b2c82017-03-06 11:45:16 -08001436 // Now that we're going to make it to the handleMessageTransaction()
1437 // call below it's safe to call updateVrFlinger(), which will
1438 // potentially trigger a display handoff.
1439 updateVrFlinger();
1440
Dan Stoza6b9454d2014-11-07 16:00:59 -08001441 bool refreshNeeded = handleMessageTransaction();
1442 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001443 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001444 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001445 // Signal a refresh if a transaction modified the window state,
1446 // a new buffer was latched, or if HWC has requested a full
1447 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001448 signalRefresh();
1449 }
1450 break;
1451 }
1452 case MessageQueue::REFRESH: {
1453 handleMessageRefresh();
1454 break;
1455 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001456 }
1457}
1458
Dan Stoza6b9454d2014-11-07 16:00:59 -08001459bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001460 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001461 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001462 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001463 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001464 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001465 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001466}
1467
Dan Stoza6b9454d2014-11-07 16:00:59 -08001468bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001469 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001470 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001471}
1472
1473void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001474 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001475
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001476 mRefreshPending = false;
1477
Pablo Ceballos40845df2016-01-25 17:41:15 -08001478 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001479
Brian Andersond6927fb2016-07-23 23:37:30 -07001480 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001481 rebuildLayerStacks();
1482 setUpHWComposer();
1483 doDebugFlashRegions();
1484 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001485 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001486
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001487 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001488
1489 mHadClientComposition = false;
1490 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1491 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1492 mHadClientComposition = mHadClientComposition ||
1493 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1494 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001495
Dan Stoza9e56aa02015-11-02 13:00:03 -08001496 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001497}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001498
Mathias Agopiancd60f992012-08-16 16:28:27 -07001499void SurfaceFlinger::doDebugFlashRegions()
1500{
1501 // is debugging enabled
1502 if (CC_LIKELY(!mDebugRegion))
1503 return;
1504
1505 const bool repaintEverything = mRepaintEverything;
1506 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1507 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001508 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509 // transform the dirty region into this screen's coordinate space
1510 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1511 if (!dirtyRegion.isEmpty()) {
1512 // redraw the whole screen
1513 doComposeSurfaces(hw, Region(hw->bounds()));
1514
1515 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001516 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001517 RenderEngine& engine(getRenderEngine());
1518 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1519
Mathias Agopianda27af92012-09-13 18:17:13 -07001520 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001521 }
1522 }
1523 }
1524
1525 postFramebuffer();
1526
1527 if (mDebugRegion > 1) {
1528 usleep(mDebugRegion * 1000);
1529 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001530
Dan Stoza9e56aa02015-11-02 13:00:03 -08001531 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001532 auto& displayDevice = mDisplays[displayId];
1533 if (!displayDevice->isDisplayOn()) {
1534 continue;
1535 }
1536
1537 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001538 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1539 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001540 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001541}
1542
Brian Andersond6927fb2016-07-23 23:37:30 -07001543void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001544{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001545 ATRACE_CALL();
1546 ALOGV("preComposition");
1547
Mathias Agopiancd60f992012-08-16 16:28:27 -07001548 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001549 mDrawingState.traverseInZOrder([&](Layer* layer) {
1550 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001551 needExtraInvalidate = true;
1552 }
Robert Carr2047fae2016-11-28 14:09:09 -08001553 });
1554
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555 if (needExtraInvalidate) {
1556 signalLayerUpdate();
1557 }
1558}
1559
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001560void SurfaceFlinger::updateCompositorTiming(
1561 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1562 std::shared_ptr<FenceTime>& presentFenceTime) {
1563 // Update queue of past composite+present times and determine the
1564 // most recently known composite to present latency.
1565 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1566 nsecs_t compositeToPresentLatency = -1;
1567 while (!mCompositePresentTimes.empty()) {
1568 CompositePresentTime& cpt = mCompositePresentTimes.front();
1569 // Cached values should have been updated before calling this method,
1570 // which helps avoid duplicate syscalls.
1571 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1572 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1573 break;
1574 }
1575 compositeToPresentLatency = displayTime - cpt.composite;
1576 mCompositePresentTimes.pop();
1577 }
1578
1579 // Don't let mCompositePresentTimes grow unbounded, just in case.
1580 while (mCompositePresentTimes.size() > 16) {
1581 mCompositePresentTimes.pop();
1582 }
1583
Brian Andersond0010582017-03-07 13:20:31 -08001584 setCompositorTimingSnapped(
1585 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1586}
1587
1588void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1589 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001590 // Integer division and modulo round toward 0 not -inf, so we need to
1591 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001592 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001593 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1594 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1595
Brian Andersond0010582017-03-07 13:20:31 -08001596 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1597 if (idealLatency <= 0) {
1598 idealLatency = vsyncInterval;
1599 }
1600
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001601 // Snap the latency to a value that removes scheduling jitter from the
1602 // composition and present times, which often have >1ms of jitter.
1603 // Reducing jitter is important if an app attempts to extrapolate
1604 // something (such as user input) to an accurate diasplay time.
1605 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1606 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001607 nsecs_t bias = vsyncInterval / 2;
1608 int64_t extraVsyncs =
1609 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1610 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1611 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001612
Brian Andersond0010582017-03-07 13:20:31 -08001613 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001614 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1615 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001616 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001617}
1618
1619void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001620{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001621 ATRACE_CALL();
1622 ALOGV("postComposition");
1623
Brian Anderson3546a3f2016-07-14 11:51:14 -07001624 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001625 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001626 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001627 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001628 }
1629
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001630 // |mStateLock| not needed as we are on the main thread
1631 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001632
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001633 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001634 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1635 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1636 glCompositionDoneFenceTime =
1637 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1638 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1639 } else {
1640 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1641 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001642
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001643 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001644 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1645 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1646 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001647
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001648 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1649 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1650
1651 // We use the refreshStartTime which might be sampled a little later than
1652 // when we started doing work for this frame, but that should be okay
1653 // since updateCompositorTiming has snapping logic.
1654 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001655 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001656 CompositorTiming compositorTiming;
1657 {
1658 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1659 compositorTiming = mCompositorTiming;
1660 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001661
Robert Carr2047fae2016-11-28 14:09:09 -08001662 mDrawingState.traverseInZOrder([&](Layer* layer) {
1663 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001664 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001665 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001666 recordBufferingStats(layer->getName().string(),
1667 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001668 }
Robert Carr2047fae2016-11-28 14:09:09 -08001669 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001670
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001671 if (presentFenceTime->isValid()) {
1672 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001673 enableHardwareVsync();
1674 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001675 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001676 }
1677 }
1678
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001679 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001680 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001681 enableHardwareVsync();
1682 }
1683 }
1684
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001685 if (mAnimCompositionPending) {
1686 mAnimCompositionPending = false;
1687
Brian Anderson4e606e32017-03-16 15:34:57 -07001688 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001689 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001690 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001691 } else {
1692 // The HWC doesn't support present fences, so use the refresh
1693 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001694 nsecs_t presentTime =
1695 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001696 mAnimFrameTracker.setActualPresentTime(presentTime);
1697 }
1698 mAnimFrameTracker.advanceFrame();
1699 }
Dan Stozab90cf072015-03-05 11:05:59 -08001700
1701 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1702 return;
1703 }
1704
1705 nsecs_t currentTime = systemTime();
1706 if (mHasPoweredOff) {
1707 mHasPoweredOff = false;
1708 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001709 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001710 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001711 if (numPeriods < NUM_BUCKETS - 1) {
1712 mFrameBuckets[numPeriods] += elapsedTime;
1713 } else {
1714 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1715 }
1716 mTotalTime += elapsedTime;
1717 }
1718 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001719}
1720
1721void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001722 ATRACE_CALL();
1723 ALOGV("rebuildLayerStacks");
1724
Mathias Agopiancd60f992012-08-16 16:28:27 -07001725 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001726 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1727 ATRACE_CALL();
1728 mVisibleRegionsDirty = false;
1729 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001730
Jeff Sharkey76488112017-02-27 14:15:18 -07001731 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1732 Region opaqueRegion;
1733 Region dirtyRegion;
1734 Vector<sp<Layer>> layersSortedByZ;
1735 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1736 const Transform& tr(displayDevice->getTransform());
1737 const Rect bounds(displayDevice->getBounds());
1738 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001739 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001740
Jeff Sharkey76488112017-02-27 14:15:18 -07001741 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001742 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1743 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001744 Region drawRegion(tr.transform(
1745 layer->visibleNonTransparentRegion));
1746 drawRegion.andSelf(bounds);
1747 if (!drawRegion.isEmpty()) {
1748 layersSortedByZ.add(layer);
1749 } else {
1750 // Clear out the HWC layer if this layer was
1751 // previously visible, but no longer is
1752 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1753 nullptr);
1754 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001755 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001756 // WM changes displayDevice->layerStack upon sleep/awake.
1757 // Here we make sure we delete the HWC layers even if
1758 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001759 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1760 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001761 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001762 });
1763 }
1764 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1765 displayDevice->undefinedRegion.set(bounds);
1766 displayDevice->undefinedRegion.subtractSelf(
1767 tr.transform(opaqueRegion));
1768 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001769 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001770 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001771}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001772
Romain Guy0147a172017-06-01 13:53:56 -07001773mat4 SurfaceFlinger::computeSaturationMatrix() const {
1774 if (mSaturation == 1.0f) {
1775 return mat4();
1776 }
1777
1778 // Rec.709 luma coefficients
1779 float3 luminance{0.213f, 0.715f, 0.072f};
1780 luminance *= 1.0f - mSaturation;
1781 return mat4(
1782 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1783 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1784 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1785 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1786 );
1787}
1788
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001789// pickColorMode translates a given dataspace into the best available color mode.
1790// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001791android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001792 switch (dataSpace) {
1793 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1794 // system expects.
1795 case HAL_DATASPACE_UNKNOWN:
1796 case HAL_DATASPACE_SRGB:
1797 case HAL_DATASPACE_V0_SRGB:
1798 return HAL_COLOR_MODE_SRGB;
1799 break;
1800
1801 case HAL_DATASPACE_DISPLAY_P3:
1802 return HAL_COLOR_MODE_DISPLAY_P3;
1803 break;
1804
1805 default:
1806 // TODO (courtneygo): Do we want to assert an error here?
1807 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1808 dataSpace);
1809 return HAL_COLOR_MODE_SRGB;
1810 break;
1811 }
1812}
1813
Romain Guy0147a172017-06-01 13:53:56 -07001814android_dataspace SurfaceFlinger::bestTargetDataSpace(
1815 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001816 // Only support sRGB and Display-P3 right now.
1817 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1818 return HAL_DATASPACE_DISPLAY_P3;
1819 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001820 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1821 return HAL_DATASPACE_DISPLAY_P3;
1822 }
1823 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1824 return HAL_DATASPACE_DISPLAY_P3;
1825 }
1826
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001827 return HAL_DATASPACE_V0_SRGB;
1828}
1829
Mathias Agopiancd60f992012-08-16 16:28:27 -07001830void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001831 ATRACE_CALL();
1832 ALOGV("setUpHWComposer");
1833
Jesse Hall028dc8f2013-08-20 16:35:32 -07001834 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001835 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1836 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1837 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1838
1839 // If nothing has changed (!dirty), don't recompose.
1840 // If something changed, but we don't currently have any visible layers,
1841 // and didn't when we last did a composition, then skip it this time.
1842 // The second rule does two things:
1843 // - When all layers are removed from a display, we'll emit one black
1844 // frame, then nothing more until we get new layers.
1845 // - When a display is created with a private layer stack, we won't
1846 // emit any black frames until a layer is added to the layer stack.
1847 bool mustRecompose = dirty && !(empty && wasEmpty);
1848
1849 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1850 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1851 mustRecompose ? "doing" : "skipping",
1852 dirty ? "+" : "-",
1853 empty ? "+" : "-",
1854 wasEmpty ? "+" : "-");
1855
Dan Stoza71433162014-02-04 16:22:36 -08001856 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001857
1858 if (mustRecompose) {
1859 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1860 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001861 }
1862
Dan Stoza9e56aa02015-11-02 13:00:03 -08001863 // build the h/w work list
1864 if (CC_UNLIKELY(mGeometryInvalid)) {
1865 mGeometryInvalid = false;
1866 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1867 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1868 const auto hwcId = displayDevice->getHwcDisplayId();
1869 if (hwcId >= 0) {
1870 const Vector<sp<Layer>>& currentLayers(
1871 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001872 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001873 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001874 if (!layer->hasHwcLayer(hwcId)) {
1875 auto hwcLayer = mHwc->createLayer(hwcId);
1876 if (hwcLayer) {
1877 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1878 } else {
1879 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001880 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001881 }
1882 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001883
Robert Carrae060832016-11-28 10:51:00 -08001884 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001885 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001887 }
1888 }
1889 }
1890 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 }
Riley Andrews03414a12014-07-01 14:22:59 -07001892
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001893
Romain Guy0147a172017-06-01 13:53:56 -07001894 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001895
Dan Stoza9e56aa02015-11-02 13:00:03 -08001896 // Set the per-frame data
1897 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1898 auto& displayDevice = mDisplays[displayId];
1899 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001900
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 if (hwcId < 0) {
1902 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001903 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001904 if (colorMatrix != mPreviousColorMatrix) {
1905 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1906 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1907 "display %zd: %d", displayId, result);
1908 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001909 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1910 layer->setPerFrameData(displayDevice);
1911 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001912
1913 if (hasWideColorDisplay) {
1914 android_color_mode newColorMode;
1915 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1916
1917 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1918 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1919 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1920 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1921 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1922 }
1923 newColorMode = pickColorMode(newDataSpace);
1924
Romain Guyc53d3552017-07-20 18:49:46 -07001925 // We want the color mode of the boot animation to match that of the bootloader
1926 // To achieve this we suppress color mode changes until after the boot animation
1927 if (mBootFinished) {
1928 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001929 displayDevice->setCompositionDataSpace(newDataSpace);
Romain Guyc53d3552017-07-20 18:49:46 -07001930 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001931 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932 }
1933
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001934 mPreviousColorMatrix = colorMatrix;
1935
Dan Stoza9e56aa02015-11-02 13:00:03 -08001936 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001937 auto& displayDevice = mDisplays[displayId];
1938 if (!displayDevice->isDisplayOn()) {
1939 continue;
1940 }
1941
1942 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001943 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1944 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001945 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001946}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001947
Mathias Agopiancd60f992012-08-16 16:28:27 -07001948void SurfaceFlinger::doComposition() {
1949 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001950 ALOGV("doComposition");
1951
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001952 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001953 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001954 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001955 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001956 // transform the dirty region into this screen's coordinate space
1957 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001958
1959 // repaint the framebuffer (if needed)
1960 doDisplayComposition(hw, dirtyRegion);
1961
Mathias Agopiancd60f992012-08-16 16:28:27 -07001962 hw->dirtyRegion.clear();
1963 hw->flip(hw->swapRegion);
1964 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001965 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001966 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001967 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001968}
1969
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001970void SurfaceFlinger::postFramebuffer()
1971{
Mathias Agopian841cde52012-03-01 15:44:37 -08001972 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001973 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001974
Mathias Agopiana44b0412011-10-16 18:46:35 -07001975 const nsecs_t now = systemTime();
1976 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001977
Dan Stoza9e56aa02015-11-02 13:00:03 -08001978 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1979 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001980 if (!displayDevice->isDisplayOn()) {
1981 continue;
1982 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001983 const auto hwcId = displayDevice->getHwcDisplayId();
1984 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001985 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001986 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001987 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001988 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001989 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1990 sp<Fence> releaseFence = Fence::NO_FENCE;
1991 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1992 releaseFence = displayDevice->getClientTargetAcquireFence();
1993 } else {
1994 auto hwcLayer = layer->getHwcLayer(hwcId);
1995 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001996 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 layer->onLayerDisplayed(releaseFence);
1998 }
1999 if (hwcId >= 0) {
2000 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002001 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002002 }
2003
Mathias Agopiana44b0412011-10-16 18:46:35 -07002004 mLastSwapBufferTime = systemTime() - now;
2005 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002006
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002007 // |mStateLock| not needed as we are on the main thread
2008 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002009 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2010 logFrameStats();
2011 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002012}
2013
Mathias Agopian87baae12012-07-31 12:38:26 -07002014void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002015{
Mathias Agopian841cde52012-03-01 15:44:37 -08002016 ATRACE_CALL();
2017
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002018 // here we keep a copy of the drawing state (that is the state that's
2019 // going to be overwritten by handleTransactionLocked()) outside of
2020 // mStateLock so that the side-effects of the State assignment
2021 // don't happen with mStateLock held (which can cause deadlocks).
2022 State drawingState(mDrawingState);
2023
Mathias Agopianca4d3602011-05-19 15:38:14 -07002024 Mutex::Autolock _l(mStateLock);
2025 const nsecs_t now = systemTime();
2026 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002027
Mathias Agopianca4d3602011-05-19 15:38:14 -07002028 // Here we're guaranteed that some transaction flags are set
2029 // so we can call handleTransactionLocked() unconditionally.
2030 // We call getTransactionFlags(), which will also clear the flags,
2031 // with mStateLock held to guarantee that mCurrentState won't change
2032 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002033
Mathias Agopiane57f2922012-08-09 16:29:12 -07002034 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002035 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002036
Mathias Agopianca4d3602011-05-19 15:38:14 -07002037 mLastTransactionTime = systemTime() - now;
2038 mDebugInTransaction = 0;
2039 invalidateHwcGeometry();
2040 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002041}
2042
Mathias Agopian87baae12012-07-31 12:38:26 -07002043void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002044{
Dan Stoza7dde5992015-05-22 09:51:44 -07002045 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002046 mCurrentState.traverseInZOrder([](Layer* layer) {
2047 layer->notifyAvailableFrames();
2048 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002049
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002050 /*
2051 * Traversal of the children
2052 * (perform the transaction for each of them if needed)
2053 */
2054
Mathias Agopian3559b072012-08-15 13:46:03 -07002055 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002056 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002057 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002058 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002059
2060 const uint32_t flags = layer->doTransaction(0);
2061 if (flags & Layer::eVisibleRegion)
2062 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002063 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002064 }
2065
2066 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002067 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002068 */
2069
Mathias Agopiane57f2922012-08-09 16:29:12 -07002070 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002071 // here we take advantage of Vector's copy-on-write semantics to
2072 // improve performance by skipping the transaction entirely when
2073 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002074 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2075 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002076 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002077 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002078 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002079 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002080
2081 // find the displays that were removed
2082 // (ie: in drawing state but not in current state)
2083 // also handle displays that changed
2084 // (ie: displays that are in both lists)
2085 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002086 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2087 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002088 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002089 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002090 // Call makeCurrent() on the primary display so we can
2091 // be sure that nothing associated with this display
2092 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002093 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002094 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002095 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002096 if (hw != NULL)
2097 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002098 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002099 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002100 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002101 } else {
2102 ALOGW("trying to remove the main display");
2103 }
2104 } else {
2105 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002106 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002107 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002108 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2109 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002110 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002111 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002112 // recreating the DisplayDevice, so we just remove it
2113 // from the drawing state, so that it get re-added
2114 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002115 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002116 if (hw != NULL)
2117 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002118 mDisplays.removeItem(display);
2119 mDrawingState.displays.removeItemsAt(i);
2120 dc--; i--;
2121 // at this point we must loop to the next item
2122 continue;
2123 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002124
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002125 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002126 if (disp != NULL) {
2127 if (state.layerStack != draw[i].layerStack) {
2128 disp->setLayerStack(state.layerStack);
2129 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002130 if ((state.orientation != draw[i].orientation)
2131 || (state.viewport != draw[i].viewport)
2132 || (state.frame != draw[i].frame))
2133 {
2134 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002135 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002136 }
Michael Lentine47e45402014-07-18 15:34:25 -07002137 if (state.width != draw[i].width || state.height != draw[i].height) {
2138 disp->setDisplaySize(state.width, state.height);
2139 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002140 }
2141 }
2142 }
2143
2144 // find displays that were added
2145 // (ie: in current state but not in drawing state)
2146 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002147 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002148 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002149
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002150 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002151 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002152 sp<IGraphicBufferProducer> bqProducer;
2153 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002154 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002155
Dan Stoza9e56aa02015-11-02 13:00:03 -08002156 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002157 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002158 // Virtual displays without a surface are dormant:
2159 // they have external state (layer stack, projection,
2160 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002161 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002162
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002163 // Allow VR composer to use virtual displays.
2164 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002165 int width = 0;
2166 int status = state.surface->query(
2167 NATIVE_WINDOW_WIDTH, &width);
2168 ALOGE_IF(status != NO_ERROR,
2169 "Unable to query width (%d)", status);
2170 int height = 0;
2171 status = state.surface->query(
2172 NATIVE_WINDOW_HEIGHT, &height);
2173 ALOGE_IF(status != NO_ERROR,
2174 "Unable to query height (%d)", status);
2175 int intFormat = 0;
2176 status = state.surface->query(
2177 NATIVE_WINDOW_FORMAT, &intFormat);
2178 ALOGE_IF(status != NO_ERROR,
2179 "Unable to query format (%d)", status);
2180 auto format = static_cast<android_pixel_format_t>(
2181 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002182
Dan Stoza8cf150a2016-08-02 10:27:31 -07002183 mHwc->allocateVirtualDisplay(width, height, &format,
2184 &hwcId);
2185 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002186
Dan Stoza5cf424b2016-05-20 14:02:39 -07002187 // TODO: Plumb requested format back up to consumer
2188
Dan Stoza9e56aa02015-11-02 13:00:03 -08002189 sp<VirtualDisplaySurface> vds =
2190 new VirtualDisplaySurface(*mHwc,
2191 hwcId, state.surface, bqProducer,
2192 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002193
2194 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002195 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002196 }
2197 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002198 ALOGE_IF(state.surface!=NULL,
2199 "adding a supported display, but rendering "
2200 "surface is provided (%p), ignoring it",
2201 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002202
2203 hwcId = state.type;
2204 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2205 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002206 }
2207
2208 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002209 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002210 sp<DisplayDevice> hw =
2211 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2212 dispSurface, producer,
2213 mRenderEngine->getEGLConfig(),
2214 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002215 hw->setLayerStack(state.layerStack);
2216 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002217 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002218 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002219 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002220 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002221 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002222 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002223 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002224 }
2225 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002226 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002227 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002228
Mathias Agopian84300952012-11-21 16:02:13 -08002229 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2230 // The transform hint might have changed for some layers
2231 // (either because a display has changed, or because a layer
2232 // as changed).
2233 //
2234 // Walk through all the layers in currentLayers,
2235 // and update their transform hint.
2236 //
2237 // If a layer is visible only on a single display, then that
2238 // display is used to calculate the hint, otherwise we use the
2239 // default display.
2240 //
2241 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2242 // the hint is set before we acquire a buffer from the surface texture.
2243 //
2244 // NOTE: layer transactions have taken place already, so we use their
2245 // drawing state. However, SurfaceFlinger's own transaction has not
2246 // happened yet, so we must use the current state layer list
2247 // (soon to become the drawing state list).
2248 //
2249 sp<const DisplayDevice> disp;
2250 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002251 bool first = true;
2252 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002253 // NOTE: we rely on the fact that layers are sorted by
2254 // layerStack first (so we don't have to traverse the list
2255 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002256 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002257 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002258 currentlayerStack = layerStack;
2259 // figure out if this layerstack is mirrored
2260 // (more than one display) if so, pick the default display,
2261 // if not, pick the only display it's on.
2262 disp.clear();
2263 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2264 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002265 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002266 if (disp == NULL) {
2267 disp = hw;
2268 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002269 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002270 break;
2271 }
2272 }
2273 }
2274 }
Chet Haase91d25932013-04-11 15:24:55 -07002275 if (disp == NULL) {
2276 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2277 // redraw after transform hint changes. See bug 8508397.
2278
2279 // could be null when this layer is using a layerStack
2280 // that is not visible on any display. Also can occur at
2281 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002282 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002283 }
Chet Haase91d25932013-04-11 15:24:55 -07002284 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002285
2286 first = false;
2287 });
Mathias Agopian84300952012-11-21 16:02:13 -08002288 }
2289
2290
Mathias Agopian3559b072012-08-15 13:46:03 -07002291 /*
2292 * Perform our own transaction if needed
2293 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002294
2295 if (mLayersAdded) {
2296 mLayersAdded = false;
2297 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002298 mVisibleRegionsDirty = true;
2299 }
2300
2301 // some layers might have been removed, so
2302 // we need to update the regions they're exposing.
2303 if (mLayersRemoved) {
2304 mLayersRemoved = false;
2305 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002306 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002307 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002308 // this layer is not visible anymore
2309 // TODO: we could traverse the tree from front to back and
2310 // compute the actual visible region
2311 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002312 Region visibleReg;
2313 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002314 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002315 }
Robert Carr2047fae2016-11-28 14:09:09 -08002316 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002317 }
2318
2319 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002320
2321 updateCursorAsync();
2322}
2323
2324void SurfaceFlinger::updateCursorAsync()
2325{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002326 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2327 auto& displayDevice = mDisplays[displayId];
2328 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002329 continue;
2330 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002331
2332 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2333 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002334 }
2335 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002336}
2337
2338void SurfaceFlinger::commitTransaction()
2339{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002340 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002341 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002342 for (const auto& l : mLayersPendingRemoval) {
2343 recordBufferingStats(l->getName().string(),
2344 l->getOccupancyHistory(true));
2345 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002346 }
2347 mLayersPendingRemoval.clear();
2348 }
2349
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002350 // If this transaction is part of a window animation then the next frame
2351 // we composite should be considered an animation as well.
2352 mAnimCompositionPending = mAnimTransactionPending;
2353
Mathias Agopian4fec8732012-06-29 14:12:52 -07002354 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002355 mDrawingState.traverseInZOrder([](Layer* layer) {
2356 layer->commitChildList();
2357 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002358 mTransactionPending = false;
2359 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002360 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361}
2362
Chia-I Wuab0c3192017-08-01 11:29:00 -07002363void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002364 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002365{
Mathias Agopian841cde52012-03-01 15:44:37 -08002366 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002367 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002368
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369 Region aboveOpaqueLayers;
2370 Region aboveCoveredLayers;
2371 Region dirty;
2372
Mathias Agopian87baae12012-07-31 12:38:26 -07002373 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002374
Robert Carr2047fae2016-11-28 14:09:09 -08002375 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002376 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002377 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002378
Jesse Hall01e29052013-02-19 16:13:35 -08002379 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002380 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002381 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002382
Mathias Agopianab028732010-03-16 16:41:46 -07002383 /*
2384 * opaqueRegion: area of a surface that is fully opaque.
2385 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002386 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002387
2388 /*
2389 * visibleRegion: area of a surface that is visible on screen
2390 * and not fully transparent. This is essentially the layer's
2391 * footprint minus the opaque regions above it.
2392 * Areas covered by a translucent surface are considered visible.
2393 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002394 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002395
2396 /*
2397 * coveredRegion: area of a surface that is covered by all
2398 * visible regions above it (which includes the translucent areas).
2399 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002400 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002401
Jesse Halla8026d22012-09-25 13:25:04 -07002402 /*
2403 * transparentRegion: area of a surface that is hinted to be completely
2404 * transparent. This is only used to tell when the layer has no visible
2405 * non-transparent regions and can be removed from the layer list. It
2406 * does not affect the visibleRegion of this layer or any layers
2407 * beneath it. The hint may not be correct if apps don't respect the
2408 * SurfaceView restrictions (which, sadly, some don't).
2409 */
2410 Region transparentRegion;
2411
Mathias Agopianab028732010-03-16 16:41:46 -07002412
2413 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002414 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002415 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002416 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002417 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002418 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002419 if (!visibleRegion.isEmpty()) {
2420 // Remove the transparent area from the visible region
2421 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002422 if (tr.preserveRects()) {
2423 // transform the transparent region
2424 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002425 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002426 // transformation too complex, can't do the
2427 // transparent region optimization.
2428 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002429 }
Mathias Agopianab028732010-03-16 16:41:46 -07002430 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002431
Mathias Agopianab028732010-03-16 16:41:46 -07002432 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002433 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002434 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002435 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2436 // the opaque region is the layer's footprint
2437 opaqueRegion = visibleRegion;
2438 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439 }
2440 }
2441
Mathias Agopianab028732010-03-16 16:41:46 -07002442 // Clip the covered region to the visible region
2443 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2444
2445 // Update aboveCoveredLayers for next (lower) layer
2446 aboveCoveredLayers.orSelf(visibleRegion);
2447
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002448 // subtract the opaque region covered by the layers above us
2449 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450
2451 // compute this layer's dirty region
2452 if (layer->contentDirty) {
2453 // we need to invalidate the whole region
2454 dirty = visibleRegion;
2455 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002456 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457 layer->contentDirty = false;
2458 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002459 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002460 * the exposed region consists of two components:
2461 * 1) what's VISIBLE now and was COVERED before
2462 * 2) what's EXPOSED now less what was EXPOSED before
2463 *
2464 * note that (1) is conservative, we start with the whole
2465 * visible region but only keep what used to be covered by
2466 * something -- which mean it may have been exposed.
2467 *
2468 * (2) handles areas that were not covered by anything but got
2469 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002470 */
Mathias Agopianab028732010-03-16 16:41:46 -07002471 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002472 const Region oldVisibleRegion = layer->visibleRegion;
2473 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002474 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2475 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002476 }
2477 dirty.subtractSelf(aboveOpaqueLayers);
2478
2479 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002480 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002481
Mathias Agopianab028732010-03-16 16:41:46 -07002482 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002483 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002484
Jesse Halla8026d22012-09-25 13:25:04 -07002485 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486 layer->setVisibleRegion(visibleRegion);
2487 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002488 layer->setVisibleNonTransparentRegion(
2489 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002490 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491
Mathias Agopian87baae12012-07-31 12:38:26 -07002492 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002493}
2494
Chia-I Wuab0c3192017-08-01 11:29:00 -07002495void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002496 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002497 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002498 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002499 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002500 }
2501 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002502}
2503
Dan Stoza6b9454d2014-11-07 16:00:59 -08002504bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002505{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002506 ALOGV("handlePageFlip");
2507
Brian Andersond6927fb2016-07-23 23:37:30 -07002508 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509
Mathias Agopian4fec8732012-06-29 14:12:52 -07002510 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002511 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002512 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002513
2514 // Store the set of layers that need updates. This set must not change as
2515 // buffers are being latched, as this could result in a deadlock.
2516 // Example: Two producers share the same command stream and:
2517 // 1.) Layer 0 is latched
2518 // 2.) Layer 0 gets a new frame
2519 // 2.) Layer 1 gets a new frame
2520 // 3.) Layer 1 is latched.
2521 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2522 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002523 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002524 if (layer->hasQueuedFrame()) {
2525 frameQueued = true;
2526 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002527 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002528 } else {
2529 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002530 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002531 } else {
2532 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002533 }
Robert Carr2047fae2016-11-28 14:09:09 -08002534 });
2535
Dan Stoza9e56aa02015-11-02 13:00:03 -08002536 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002537 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002538 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002539 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002540 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002541 newDataLatched = true;
2542 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002543 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002544
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002545 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002546
2547 // If we will need to wake up at some time in the future to deal with a
2548 // queued frame that shouldn't be displayed during this vsync period, wake
2549 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002550 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002551 signalLayerUpdate();
2552 }
2553
2554 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002555 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556}
2557
Mathias Agopianad456f92011-01-13 17:53:01 -08002558void SurfaceFlinger::invalidateHwcGeometry()
2559{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002560 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002561}
2562
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002563
Fabien Sanglard830b8472016-11-30 16:35:58 -08002564void SurfaceFlinger::doDisplayComposition(
2565 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002566 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567{
Dan Stoza71433162014-02-04 16:22:36 -08002568 // We only need to actually compose the display if:
2569 // 1) It is being handled by hardware composer, which may need this to
2570 // keep its virtual display state machine in sync, or
2571 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002572 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002573 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002574 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002575 return;
2576 }
2577
Dan Stoza9e56aa02015-11-02 13:00:03 -08002578 ALOGV("doDisplayComposition");
2579
Mathias Agopian87baae12012-07-31 12:38:26 -07002580 Region dirtyRegion(inDirtyRegion);
2581
Mathias Agopianb8a55602009-06-26 19:06:36 -07002582 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002583 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002584
Fabien Sanglard830b8472016-11-30 16:35:58 -08002585 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002586 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002587 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2588 // takes a rectangle, we must make sure to update that whole
2589 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002590 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002591 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002592 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002593 // We need to redraw the rectangle that will be updated
2594 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002595 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002596 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002597 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002598 } else {
2599 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002600 dirtyRegion.set(displayDevice->bounds());
2601 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602 }
2603 }
2604
Fabien Sanglard830b8472016-11-30 16:35:58 -08002605 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002607 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002608 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002609
2610 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002611 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612}
2613
Dan Stoza9e56aa02015-11-02 13:00:03 -08002614bool SurfaceFlinger::doComposeSurfaces(
2615 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002616{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002617 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002618
Dan Stoza9e56aa02015-11-02 13:00:03 -08002619 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002620
2621 mat4 oldColorMatrix;
2622 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2623 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2624 if (applyColorMatrix) {
2625 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2626 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2627 }
2628
Dan Stoza9e56aa02015-11-02 13:00:03 -08002629 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2630 if (hasClientComposition) {
2631 ALOGV("hasClientComposition");
2632
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002633#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002634 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002635 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002636#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002637 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002638 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002639 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002640 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002641
2642 // |mStateLock| not needed as we are on the main thread
2643 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002644 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2645 }
2646 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002647 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002648
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002649 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002650 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2651 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002652 // when using overlays, we assume a fully transparent framebuffer
2653 // NOTE: we could reduce how much we need to clear, for instance
2654 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002655 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002656 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002657 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002658 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002659 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002660 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002661
2662 // we remove the scissor part
2663 // we're left with the letterbox region
2664 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002665 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002666
2667 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002668 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002669
2670 // but limit it to the dirty region
2671 region.andSelf(dirty);
2672
Mathias Agopianb9494d52012-04-18 02:28:45 -07002673 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002674 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002675 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002676 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002677 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002678 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002679
Dan Stoza9e56aa02015-11-02 13:00:03 -08002680 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002681 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002682 // scissor on the main display. It should never be needed
2683 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002684 const Rect& bounds(displayDevice->getBounds());
2685 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002686 if (scissor != bounds) {
2687 // scissor doesn't match the screen's dimensions, so we
2688 // need to clear everything outside of it and enable
2689 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002690
Mathias Agopianf45c5102012-10-24 16:29:17 -07002691 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002692 const uint32_t height = displayDevice->getHeight();
2693 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002694 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002695 }
2696 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002697 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002698
Mathias Agopian85d751c2012-08-29 16:59:24 -07002699 /*
2700 * and then, render the layers targeted at the framebuffer
2701 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002702
Dan Stoza9e56aa02015-11-02 13:00:03 -08002703 ALOGV("Rendering client layers");
2704 const Transform& displayTransform = displayDevice->getTransform();
2705 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002706 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002707 bool firstLayer = true;
2708 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2709 const Region clip(dirty.intersect(
2710 displayTransform.transform(layer->visibleRegion)));
2711 ALOGV("Layer: %s", layer->getName().string());
2712 ALOGV(" Composition type: %s",
2713 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002714 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002715 switch (layer->getCompositionType(hwcId)) {
2716 case HWC2::Composition::Cursor:
2717 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002718 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002719 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002720 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002721 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2722 layer->isOpaque(state) && (state.alpha == 1.0f)
2723 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002724 // never clear the very first layer since we're
2725 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002726 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002727 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002728 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002729 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002730 case HWC2::Composition::Client: {
2731 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002732 break;
2733 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002734 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002735 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002736 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002737 } else {
2738 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002739 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002741 }
2742 } else {
2743 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002744 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002745 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002746 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002747 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002748 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002749 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002750 }
2751 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002752
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002753 if (applyColorMatrix) {
2754 getRenderEngine().setupColorTransform(oldColorMatrix);
2755 }
2756
Mathias Agopianf45c5102012-10-24 16:29:17 -07002757 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002758 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002759 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760}
2761
Fabien Sanglard830b8472016-11-30 16:35:58 -08002762void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2763 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002764 RenderEngine& engine(getRenderEngine());
2765 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766}
2767
Dan Stoza7d89d062015-04-30 13:29:25 -07002768status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002769 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002770 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002771 const sp<Layer>& lbc,
2772 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002773{
Dan Stoza7d89d062015-04-30 13:29:25 -07002774 // add this layer to the current state list
2775 {
2776 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002777 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002778 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2779 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002780 return NO_MEMORY;
2781 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002782 if (parent == nullptr) {
2783 mCurrentState.layersSortedByZ.add(lbc);
2784 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002785 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2786 ALOGE("addClientLayer called with a removed parent");
2787 return NAME_NOT_FOUND;
2788 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002789 parent->addChild(lbc);
2790 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002791
Dan Stoza7d89d062015-04-30 13:29:25 -07002792 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002793 mLayersAdded = true;
2794 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002795 }
2796
Mathias Agopian96f08192010-06-02 23:28:45 -07002797 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002798 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002799
Dan Stoza7d89d062015-04-30 13:29:25 -07002800 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002801}
2802
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002803status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002804 Mutex::Autolock _l(mStateLock);
2805
Robert Carr1f0a16a2016-10-24 16:27:39 -07002806 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002807 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002808 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002809 if (topLevelOnly) {
2810 return NO_ERROR;
2811 }
2812
Chia-I Wu98f1c102017-05-30 14:54:08 -07002813 sp<Layer> ancestor = p;
2814 while (ancestor->getParent() != nullptr) {
2815 ancestor = ancestor->getParent();
2816 }
2817 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2818 ALOGE("removeLayer called with a layer whose parent has been removed");
2819 return NAME_NOT_FOUND;
2820 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002821
2822 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002823 } else {
2824 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002825 }
2826
Robert Carr136e2f62017-02-08 17:54:29 -08002827 // As a matter of normal operation, the LayerCleaner will produce a second
2828 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2829 // so we will succeed in promoting it, but it's already been removed
2830 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2831 // otherwise something has gone wrong and we are leaking the layer.
2832 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002833 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2834 layer->getName().string(),
2835 (p != nullptr) ? p->getName().string() : "no-parent");
2836 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002837 } else if (index < 0) {
2838 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002839 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002840
2841 mLayersPendingRemoval.add(layer);
2842 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002843 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002844 setTransactionFlags(eTransactionNeeded);
2845 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002846}
2847
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002848uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002849 return android_atomic_release_load(&mTransactionFlags);
2850}
2851
Mathias Agopian3f844832013-08-07 21:24:32 -07002852uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2854}
2855
Mathias Agopian3f844832013-08-07 21:24:32 -07002856uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2858 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002859 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860 }
2861 return old;
2862}
2863
Mathias Agopian8b33f032012-07-24 20:43:54 -07002864void SurfaceFlinger::setTransactionState(
2865 const Vector<ComposerState>& state,
2866 const Vector<DisplayState>& displays,
2867 uint32_t flags)
2868{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002869 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002870 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002871 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002872
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002873 if (flags & eAnimation) {
2874 // For window updates that are part of an animation we must wait for
2875 // previous animation "frames" to be handled.
2876 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002877 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002878 if (CC_UNLIKELY(err != NO_ERROR)) {
2879 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002880 // caller after a few seconds.
2881 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2882 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002883 mAnimTransactionPending = false;
2884 break;
2885 }
2886 }
2887 }
2888
Mathias Agopiane57f2922012-08-09 16:29:12 -07002889 size_t count = displays.size();
2890 for (size_t i=0 ; i<count ; i++) {
2891 const DisplayState& s(displays[i]);
2892 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002893 }
2894
Mathias Agopiane57f2922012-08-09 16:29:12 -07002895 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002896 for (size_t i=0 ; i<count ; i++) {
2897 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002898 // Here we need to check that the interface we're given is indeed
2899 // one of our own. A malicious client could give us a NULL
2900 // IInterface, or one of its own or even one of our own but a
2901 // different type. All these situations would cause us to crash.
2902 //
2903 // NOTE: it would be better to use RTTI as we could directly check
2904 // that we have a Client*. however, RTTI is disabled in Android.
2905 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002906 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002907 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002908 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002909 sp<Client> client( static_cast<Client *>(s.client.get()) );
2910 transactionFlags |= setClientStateLocked(client, s.state);
2911 }
2912 }
2913 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002914 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002915
Robert Carr2a7dbb42016-05-24 11:41:28 -07002916 // If a synchronous transaction is explicitly requested without any changes,
2917 // force a transaction anyway. This can be used as a flush mechanism for
2918 // previous async transactions.
2919 if (transactionFlags == 0 && (flags & eSynchronous)) {
2920 transactionFlags = eTransactionNeeded;
2921 }
2922
Mathias Agopian386aa982011-11-07 21:58:03 -08002923 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002924 if (mInterceptor.isEnabled()) {
2925 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2926 }
Irvel468051e2016-06-13 16:44:44 -07002927
Mathias Agopian386aa982011-11-07 21:58:03 -08002928 // this triggers the transaction
2929 setTransactionFlags(transactionFlags);
2930
2931 // if this is a synchronous transaction, wait for it to take effect
2932 // before returning.
2933 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002934 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002935 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002936 if (flags & eAnimation) {
2937 mAnimTransactionPending = true;
2938 }
2939 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002940 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2941 if (CC_UNLIKELY(err != NO_ERROR)) {
2942 // just in case something goes wrong in SF, return to the
2943 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002944 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2945 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002946 break;
2947 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002948 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002949 }
2950}
2951
Mathias Agopiane57f2922012-08-09 16:29:12 -07002952uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2953{
Jesse Hall9a143922012-10-04 16:29:19 -07002954 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2955 if (dpyIdx < 0)
2956 return 0;
2957
Mathias Agopiane57f2922012-08-09 16:29:12 -07002958 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002959 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002960 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002961 const uint32_t what = s.what;
2962 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002963 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002964 disp.surface = s.surface;
2965 flags |= eDisplayTransactionNeeded;
2966 }
2967 }
2968 if (what & DisplayState::eLayerStackChanged) {
2969 if (disp.layerStack != s.layerStack) {
2970 disp.layerStack = s.layerStack;
2971 flags |= eDisplayTransactionNeeded;
2972 }
2973 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002974 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002975 if (disp.orientation != s.orientation) {
2976 disp.orientation = s.orientation;
2977 flags |= eDisplayTransactionNeeded;
2978 }
2979 if (disp.frame != s.frame) {
2980 disp.frame = s.frame;
2981 flags |= eDisplayTransactionNeeded;
2982 }
2983 if (disp.viewport != s.viewport) {
2984 disp.viewport = s.viewport;
2985 flags |= eDisplayTransactionNeeded;
2986 }
2987 }
Michael Lentine47e45402014-07-18 15:34:25 -07002988 if (what & DisplayState::eDisplaySizeChanged) {
2989 if (disp.width != s.width) {
2990 disp.width = s.width;
2991 flags |= eDisplayTransactionNeeded;
2992 }
2993 if (disp.height != s.height) {
2994 disp.height = s.height;
2995 flags |= eDisplayTransactionNeeded;
2996 }
2997 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002998 }
2999 return flags;
3000}
3001
3002uint32_t SurfaceFlinger::setClientStateLocked(
3003 const sp<Client>& client,
3004 const layer_state_t& s)
3005{
3006 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003007 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003008 if (layer != 0) {
3009 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003010 bool geometryAppliesWithResize =
3011 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003012 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003013 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003014 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003015 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003016 }
3017 if (what & layer_state_t::eLayerChanged) {
3018 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003019 const auto& p = layer->getParent();
3020 if (p == nullptr) {
3021 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3022 if (layer->setLayer(s.z) && idx >= 0) {
3023 mCurrentState.layersSortedByZ.removeAt(idx);
3024 mCurrentState.layersSortedByZ.add(layer);
3025 // we need traversal (state changed)
3026 // AND transaction (list changed)
3027 flags |= eTransactionNeeded|eTraversalNeeded;
3028 }
3029 } else {
3030 if (p->setChildLayer(layer, s.z)) {
3031 flags |= eTransactionNeeded|eTraversalNeeded;
3032 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003033 }
3034 }
Robert Carrdb66e622017-04-10 16:55:57 -07003035 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003036 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003037 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003038 mCurrentState.layersSortedByZ.removeAt(idx);
3039 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003040 flags |= eTransactionNeeded|eTraversalNeeded;
3041 }
3042 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003043 if (what & layer_state_t::eSizeChanged) {
3044 if (layer->setSize(s.w, s.h)) {
3045 flags |= eTraversalNeeded;
3046 }
3047 }
3048 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003049 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003050 flags |= eTraversalNeeded;
3051 }
3052 if (what & layer_state_t::eMatrixChanged) {
3053 if (layer->setMatrix(s.matrix))
3054 flags |= eTraversalNeeded;
3055 }
3056 if (what & layer_state_t::eTransparentRegionChanged) {
3057 if (layer->setTransparentRegionHint(s.transparentRegion))
3058 flags |= eTraversalNeeded;
3059 }
Dan Stoza23116082015-06-18 14:58:39 -07003060 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003061 if (layer->setFlags(s.flags, s.mask))
3062 flags |= eTraversalNeeded;
3063 }
3064 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003065 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003066 flags |= eTraversalNeeded;
3067 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003068 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003069 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003070 flags |= eTraversalNeeded;
3071 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003072 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003073 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003074 // We only allow setting layer stacks for top level layers,
3075 // everything else inherits layer stack from its parent.
3076 if (layer->hasParent()) {
3077 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3078 layer->getName().string());
3079 } else if (idx < 0) {
3080 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3081 "that also does not appear in the top level layer list. Something"
3082 " has gone wrong.", layer->getName().string());
3083 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003084 mCurrentState.layersSortedByZ.removeAt(idx);
3085 mCurrentState.layersSortedByZ.add(layer);
3086 // we need traversal (state changed)
3087 // AND transaction (list changed)
3088 flags |= eTransactionNeeded|eTraversalNeeded;
3089 }
3090 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003091 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003092 if (s.barrierHandle != nullptr) {
3093 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3094 } else if (s.barrierGbp != nullptr) {
3095 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3096 if (authenticateSurfaceTextureLocked(gbp)) {
3097 const auto& otherLayer =
3098 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3099 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3100 } else {
3101 ALOGE("Attempt to defer transaction to to an"
3102 " unrecognized GraphicBufferProducer");
3103 }
3104 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003105 // We don't trigger a traversal here because if no other state is
3106 // changed, we don't want this to cause any more work
3107 }
Robert Carr1db73f62016-12-21 12:58:51 -08003108 if (what & layer_state_t::eReparentChildren) {
3109 if (layer->reparentChildren(s.reparentHandle)) {
3110 flags |= eTransactionNeeded|eTraversalNeeded;
3111 }
3112 }
Robert Carr9524cb32017-02-13 11:32:32 -08003113 if (what & layer_state_t::eDetachChildren) {
3114 layer->detachChildren();
3115 }
Robert Carrc3574f72016-03-24 12:19:32 -07003116 if (what & layer_state_t::eOverrideScalingModeChanged) {
3117 layer->setOverrideScalingMode(s.overrideScalingMode);
3118 // We don't trigger a traversal here because if no other state is
3119 // changed, we don't want this to cause any more work
3120 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003121 }
3122 return flags;
3123}
3124
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003125status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003126 const String8& name,
3127 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003128 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003129 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3130 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003132 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003133 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003134 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003135 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003136 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003137
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003138 status_t result = NO_ERROR;
3139
3140 sp<Layer> layer;
3141
Cody Northropbc755282017-03-31 12:00:08 -06003142 String8 uniqueName = getUniqueLayerName(name);
3143
Mathias Agopian3165cc22012-08-08 19:42:09 -07003144 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3145 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003146 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003147 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003148 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003149 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003150 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003151 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003152 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003153 handle, gbp, &layer);
3154 break;
3155 default:
3156 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 break;
3158 }
3159
Dan Stoza7d89d062015-04-30 13:29:25 -07003160 if (result != NO_ERROR) {
3161 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003163
Chia-I Wuab0c3192017-08-01 11:29:00 -07003164 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3165 // TODO b/64227542
3166 if (windowType == 441731) {
3167 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3168 layer->setPrimaryDisplayOnly();
3169 }
3170
Albert Chaulk479c60c2017-01-27 14:21:34 -05003171 layer->setInfo(windowType, ownerUid);
3172
Robert Carr1f0a16a2016-10-24 16:27:39 -07003173 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003174 if (result != NO_ERROR) {
3175 return result;
3176 }
Irvelffc9efc2016-07-27 15:16:37 -07003177 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003178
3179 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003180 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003181}
3182
Cody Northropbc755282017-03-31 12:00:08 -06003183String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3184{
3185 bool matchFound = true;
3186 uint32_t dupeCounter = 0;
3187
3188 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3189 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3190
3191 // Loop over layers until we're sure there is no matching name
3192 while (matchFound) {
3193 matchFound = false;
3194 mDrawingState.traverseInZOrder([&](Layer* layer) {
3195 if (layer->getName() == uniqueName) {
3196 matchFound = true;
3197 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3198 }
3199 });
3200 }
3201
3202 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3203
3204 return uniqueName;
3205}
3206
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003207status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3208 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3209 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210{
3211 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003212 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003213 case PIXEL_FORMAT_TRANSPARENT:
3214 case PIXEL_FORMAT_TRANSLUCENT:
3215 format = PIXEL_FORMAT_RGBA_8888;
3216 break;
3217 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003218 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219 break;
3220 }
3221
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003222 *outLayer = new Layer(this, client, name, w, h, flags);
3223 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3224 if (err == NO_ERROR) {
3225 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003226 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003228
3229 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3230 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003231}
3232
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003233status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3234 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3235 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003237 *outLayer = new LayerDim(this, client, name, w, h, flags);
3238 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003239 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003240 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003241}
3242
Mathias Agopianac9fa422013-02-11 16:40:36 -08003243status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003244{
Robert Carr9524cb32017-02-13 11:32:32 -08003245 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003246 status_t err = NO_ERROR;
3247 sp<Layer> l(client->getLayerUser(handle));
3248 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003249 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003250 err = removeLayer(l);
3251 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3252 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003253 }
3254 return err;
3255}
3256
Mathias Agopian13127d82013-03-05 17:47:11 -08003257status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003258{
Mathias Agopian67106042013-03-14 19:18:13 -07003259 // called by ~LayerCleaner() when all references to the IBinder (handle)
3260 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003261 sp<Layer> l = layer.promote();
3262 if (l == nullptr) {
3263 // The layer has already been removed, carry on
3264 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003265 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003266 // If we have a parent, then we can continue to live as long as it does.
3267 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268}
3269
Mathias Agopianb60314a2012-04-10 22:09:54 -07003270// ---------------------------------------------------------------------------
3271
Andy McFadden13a082e2012-08-24 10:16:42 -07003272void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003273 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003274 Vector<ComposerState> state;
3275 Vector<DisplayState> displays;
3276 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003277 d.what = DisplayState::eDisplayProjectionChanged |
3278 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003279 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003280 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003281 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003282 d.frame.makeInvalid();
3283 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003284 d.width = 0;
3285 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003286 displays.add(d);
3287 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003288 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003289
Dan Stoza9e56aa02015-11-02 13:00:03 -08003290 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3291 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003292 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003293
Brian Andersond0010582017-03-07 13:20:31 -08003294 // Use phase of 0 since phase is not known.
3295 // Use latency of 0, which will snap to the ideal latency.
3296 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003297}
3298
3299void SurfaceFlinger::initializeDisplays() {
3300 class MessageScreenInitialized : public MessageBase {
3301 SurfaceFlinger* flinger;
3302 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003303 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003304 virtual bool handler() {
3305 flinger->onInitializeDisplays();
3306 return true;
3307 }
3308 };
3309 sp<MessageBase> msg = new MessageScreenInitialized(this);
3310 postMessageAsync(msg); // we may be called from main thread, use async message
3311}
3312
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003313void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3314 int mode) {
3315 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3316 this);
3317 int32_t type = hw->getDisplayType();
3318 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003319
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003320 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003321 return;
3322 }
3323
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003324 hw->setPowerMode(mode);
3325 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3326 ALOGW("Trying to set power mode for virtual display");
3327 return;
3328 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003329
Irvelffc9efc2016-07-27 15:16:37 -07003330 if (mInterceptor.isEnabled()) {
3331 Mutex::Autolock _l(mStateLock);
3332 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3333 if (idx < 0) {
3334 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3335 return;
3336 }
3337 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3338 }
3339
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003340 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003341 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003342 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003343 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3344 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003345 // FIXME: eventthread only knows about the main display right now
3346 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003347 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003348 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003349
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003350 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003351 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003352 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003353
3354 struct sched_param param = {0};
3355 param.sched_priority = 1;
3356 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3357 ALOGW("Couldn't set SCHED_FIFO on display on");
3358 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003359 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003360 // Turn off the display
3361 struct sched_param param = {0};
3362 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3363 ALOGW("Couldn't set SCHED_OTHER on display off");
3364 }
3365
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003366 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003367 disableHardwareVsync(true); // also cancels any in-progress resync
3368
Mathias Agopiancde87a32012-09-13 14:09:01 -07003369 // FIXME: eventthread only knows about the main display right now
3370 mEventThread->onScreenReleased();
3371 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003372
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003373 getHwComposer().setPowerMode(type, mode);
3374 mVisibleRegionsDirty = true;
3375 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003376 } else if (mode == HWC_POWER_MODE_DOZE ||
3377 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003378 // Update display while dozing
3379 getHwComposer().setPowerMode(type, mode);
3380 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3381 // FIXME: eventthread only knows about the main display right now
3382 mEventThread->onScreenAcquired();
3383 resyncToHardwareVsync(true);
3384 }
3385 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3386 // Leave display going to doze
3387 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3388 disableHardwareVsync(true); // also cancels any in-progress resync
3389 // FIXME: eventthread only knows about the main display right now
3390 mEventThread->onScreenReleased();
3391 }
3392 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003393 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003394 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003395 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003396 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003397}
3398
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003399void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3400 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003401 SurfaceFlinger& mFlinger;
3402 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003403 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003404 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003405 MessageSetPowerMode(SurfaceFlinger& flinger,
3406 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3407 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003408 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003409 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003410 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003411 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003412 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003413 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003414 ALOGW("Attempt to set power mode = %d for virtual display",
3415 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003416 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003417 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003418 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003419 return true;
3420 }
3421 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003422 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003423 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003424}
3425
3426// ---------------------------------------------------------------------------
3427
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003428status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3429{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003430 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003431
Mathias Agopianbd115332013-04-18 16:41:04 -07003432 IPCThreadState* ipc = IPCThreadState::self();
3433 const int pid = ipc->getCallingPid();
3434 const int uid = ipc->getCallingUid();
3435 if ((uid != AID_SHELL) &&
3436 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003437 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003438 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003439 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003440 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003441 // (this would indicate SF is stuck, but we want to be able to
3442 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003443 status_t err = mStateLock.timedLock(s2ns(1));
3444 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003445 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003446 result.appendFormat(
3447 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3448 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003449 }
3450
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003451 bool dumpAll = true;
3452 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003453 size_t numArgs = args.size();
3454 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003455 if ((index < numArgs) &&
3456 (args[index] == String16("--list"))) {
3457 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003458 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003459 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003460 }
3461
3462 if ((index < numArgs) &&
3463 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003464 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003465 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003466 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003467 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003468
3469 if ((index < numArgs) &&
3470 (args[index] == String16("--latency-clear"))) {
3471 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003472 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003473 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003474 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003475
3476 if ((index < numArgs) &&
3477 (args[index] == String16("--dispsync"))) {
3478 index++;
3479 mPrimaryDispSync.dump(result);
3480 dumpAll = false;
3481 }
Dan Stozab90cf072015-03-05 11:05:59 -08003482
3483 if ((index < numArgs) &&
3484 (args[index] == String16("--static-screen"))) {
3485 index++;
3486 dumpStaticScreenStats(result);
3487 dumpAll = false;
3488 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003489
3490 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003491 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003492 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003493 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003494 dumpAll = false;
3495 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003496
3497 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3498 index++;
3499 dumpWideColorInfo(result);
3500 dumpAll = false;
3501 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003502 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003503
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003504 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003505 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003506 }
3507
Mathias Agopian9795c422009-08-26 16:36:26 -07003508 if (locked) {
3509 mStateLock.unlock();
3510 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511 }
3512 write(fd, result.string(), result.size());
3513 return NO_ERROR;
3514}
3515
Dan Stozac7014012014-02-14 15:03:43 -08003516void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3517 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003518{
Robert Carr2047fae2016-11-28 14:09:09 -08003519 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003520 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003521 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003522}
3523
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003524void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003525 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003526{
3527 String8 name;
3528 if (index < args.size()) {
3529 name = String8(args[index]);
3530 index++;
3531 }
3532
Dan Stoza9e56aa02015-11-02 13:00:03 -08003533 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3534 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003535 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003536
3537 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003538 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003539 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003540 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003541 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003542 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003543 }
Robert Carr2047fae2016-11-28 14:09:09 -08003544 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003545 }
3546}
3547
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003548void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003549 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003550{
3551 String8 name;
3552 if (index < args.size()) {
3553 name = String8(args[index]);
3554 index++;
3555 }
3556
Robert Carr2047fae2016-11-28 14:09:09 -08003557 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003558 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003559 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003560 }
Robert Carr2047fae2016-11-28 14:09:09 -08003561 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003562
Svetoslavd85084b2014-03-20 10:28:31 -07003563 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003564}
3565
Jamie Gennis6547ff42013-07-16 20:12:42 -07003566// This should only be called from the main thread. Otherwise it would need
3567// the lock and should use mCurrentState rather than mDrawingState.
3568void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003569 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003570 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003571 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003572
3573 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3574}
3575
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003576void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003577{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003578 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003579 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3580
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003581 if (isLayerTripleBufferingDisabled())
3582 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003583
3584 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003585 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003586 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003587 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003588 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3589 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003590 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003591}
3592
Dan Stozab90cf072015-03-05 11:05:59 -08003593void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3594{
3595 result.appendFormat("Static screen stats:\n");
3596 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3597 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3598 float percent = 100.0f *
3599 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3600 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3601 b + 1, bucketTimeSec, percent);
3602 }
3603 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3604 float percent = 100.0f *
3605 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3606 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3607 NUM_BUCKETS - 1, bucketTimeSec, percent);
3608}
3609
Dan Stozae77c7662016-05-13 11:37:28 -07003610void SurfaceFlinger::recordBufferingStats(const char* layerName,
3611 std::vector<OccupancyTracker::Segment>&& history) {
3612 Mutex::Autolock lock(mBufferingStatsMutex);
3613 auto& stats = mBufferingStats[layerName];
3614 for (const auto& segment : history) {
3615 if (!segment.usedThirdBuffer) {
3616 stats.twoBufferTime += segment.totalTime;
3617 }
3618 if (segment.occupancyAverage < 1.0f) {
3619 stats.doubleBufferedTime += segment.totalTime;
3620 } else if (segment.occupancyAverage < 2.0f) {
3621 stats.tripleBufferedTime += segment.totalTime;
3622 }
3623 ++stats.numSegments;
3624 stats.totalTime += segment.totalTime;
3625 }
3626}
3627
Brian Andersond6927fb2016-07-23 23:37:30 -07003628void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3629 result.appendFormat("Layer frame timestamps:\n");
3630
3631 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3632 const size_t count = currentLayers.size();
3633 for (size_t i=0 ; i<count ; i++) {
3634 currentLayers[i]->dumpFrameEvents(result);
3635 }
3636}
3637
Dan Stozae77c7662016-05-13 11:37:28 -07003638void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3639 result.append("Buffering stats:\n");
3640 result.append(" [Layer name] <Active time> <Two buffer> "
3641 "<Double buffered> <Triple buffered>\n");
3642 Mutex::Autolock lock(mBufferingStatsMutex);
3643 typedef std::tuple<std::string, float, float, float> BufferTuple;
3644 std::map<float, BufferTuple, std::greater<float>> sorted;
3645 for (const auto& statsPair : mBufferingStats) {
3646 const char* name = statsPair.first.c_str();
3647 const BufferingStats& stats = statsPair.second;
3648 if (stats.numSegments == 0) {
3649 continue;
3650 }
3651 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3652 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3653 stats.totalTime;
3654 float doubleBufferRatio = static_cast<float>(
3655 stats.doubleBufferedTime) / stats.totalTime;
3656 float tripleBufferRatio = static_cast<float>(
3657 stats.tripleBufferedTime) / stats.totalTime;
3658 sorted.insert({activeTime, {name, twoBufferRatio,
3659 doubleBufferRatio, tripleBufferRatio}});
3660 }
3661 for (const auto& sortedPair : sorted) {
3662 float activeTime = sortedPair.first;
3663 const BufferTuple& values = sortedPair.second;
3664 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3665 std::get<0>(values).c_str(), activeTime,
3666 std::get<1>(values), std::get<2>(values),
3667 std::get<3>(values));
3668 }
3669 result.append("\n");
3670}
3671
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003672void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3673 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3674
3675 // TODO: print out if wide-color mode is active or not
3676
3677 for (size_t d = 0; d < mDisplays.size(); d++) {
3678 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3679 int32_t hwcId = displayDevice->getHwcDisplayId();
3680 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3681 continue;
3682 }
3683
3684 result.appendFormat("Display %d color modes:\n", hwcId);
3685 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3686 for (auto&& mode : modes) {
3687 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3688 }
3689
3690 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3691 result.appendFormat(" Current color mode: %s (%d)\n",
3692 decodeColorMode(currentMode).c_str(), currentMode);
3693 }
3694 result.append("\n");
3695}
3696
Mathias Agopian74d211a2013-04-22 16:55:35 +02003697void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3698 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003699{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003700 bool colorize = false;
3701 if (index < args.size()
3702 && (args[index] == String16("--color"))) {
3703 colorize = true;
3704 index++;
3705 }
3706
3707 Colorizer colorizer(colorize);
3708
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003709 // figure out if we're stuck somewhere
3710 const nsecs_t now = systemTime();
3711 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3712 const nsecs_t inTransaction(mDebugInTransaction);
3713 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3714 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3715
3716 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003717 * Dump library configuration.
3718 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003719
3720 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003721 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003722 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003723 appendSfConfigString(result);
3724 appendUiConfigString(result);
3725 appendGuiConfigString(result);
3726 result.append("\n");
3727
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003728 result.append("\nWide-Color information:\n");
3729 dumpWideColorInfo(result);
3730
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003731 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003732 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003733 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003734 result.append(SyncFeatures::getInstance().toString());
3735 result.append("\n");
3736
Dan Stoza9e56aa02015-11-02 13:00:03 -08003737 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3738
Andy McFadden41d67d72014-04-25 16:58:34 -07003739 colorizer.bold(result);
3740 result.append("DispSync configuration: ");
3741 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003742 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003743 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003744 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003745 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003746 result.append("\n");
3747
Dan Stozab90cf072015-03-05 11:05:59 -08003748 // Dump static screen stats
3749 result.append("\n");
3750 dumpStaticScreenStats(result);
3751 result.append("\n");
3752
Dan Stozae77c7662016-05-13 11:37:28 -07003753 dumpBufferingStats(result);
3754
Andy McFadden4803b742012-09-24 19:07:20 -07003755 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003756 * Dump the visible layer list
3757 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003758 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003759 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003760 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003761 mCurrentState.traverseInZOrder([&](Layer* layer) {
Kalle Raitaa099a242017-01-11 11:17:29 -08003762 result.append(to_string(layer->getLayerDebugInfo()).c_str());
Robert Carr2047fae2016-11-28 14:09:09 -08003763 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003764
3765 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003766 * Dump Display state
3767 */
3768
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003769 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003770 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003771 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003772 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3773 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003774 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003775 }
3776
3777 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003778 * Dump SurfaceFlinger global state
3779 */
3780
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003781 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003782 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003783 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003784
Mathias Agopian888c8222012-08-04 21:10:38 -07003785 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003786 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003787
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003788 colorizer.bold(result);
3789 result.appendFormat("EGL implementation : %s\n",
3790 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3791 colorizer.reset(result);
3792 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003793 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003794
Mathias Agopian875d8e12013-06-07 15:35:48 -07003795 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003796
Mathias Agopian42977342012-08-05 00:40:46 -07003797 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003798 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3799 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003800 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003801 " last eglSwapBuffers() time: %f us\n"
3802 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003803 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003804 " refresh-rate : %f fps\n"
3805 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003806 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003807 " gpu_to_cpu_unsupported : %d\n"
3808 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003809 mLastSwapBufferTime/1000.0,
3810 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003811 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003812 1e9 / activeConfig->getVsyncPeriod(),
3813 activeConfig->getDpiX(),
3814 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003815 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003816
Mathias Agopian74d211a2013-04-22 16:55:35 +02003817 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003818 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003819
Mathias Agopian74d211a2013-04-22 16:55:35 +02003820 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003821 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003822
3823 /*
3824 * VSYNC state
3825 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003826 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003827 result.append("\n");
3828
3829 /*
3830 * HWC layer minidump
3831 */
3832 for (size_t d = 0; d < mDisplays.size(); d++) {
3833 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3834 int32_t hwcId = displayDevice->getHwcDisplayId();
3835 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3836 continue;
3837 }
3838
3839 result.appendFormat("Display %d HWC layers:\n", hwcId);
3840 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003841 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003842 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003843 });
Dan Stozae22aec72016-08-01 13:20:59 -07003844 result.append("\n");
3845 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003846
3847 /*
3848 * Dump HWComposer state
3849 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003850 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003851 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003852 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003853 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003854 result.appendFormat(" h/w composer %s\n",
3855 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003856 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003857
3858 /*
3859 * Dump gralloc state
3860 */
3861 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3862 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003863
3864 /*
3865 * Dump VrFlinger state if in use.
3866 */
3867 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3868 result.append("VrFlinger state:\n");
3869 result.append(mVrFlinger->Dump().c_str());
3870 result.append("\n");
3871 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003872}
3873
Mathias Agopian13127d82013-03-05 17:47:11 -08003874const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003875SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003876 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003877 wp<IBinder> dpy;
3878 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3879 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3880 dpy = mDisplays.keyAt(i);
3881 break;
3882 }
3883 }
3884 if (dpy == NULL) {
3885 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3886 // Just use the primary display so we have something to return
3887 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3888 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003889 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003890}
3891
Keun young Park63f165f2012-08-31 10:53:36 -07003892bool SurfaceFlinger::startDdmConnection()
3893{
3894 void* libddmconnection_dso =
3895 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3896 if (!libddmconnection_dso) {
3897 return false;
3898 }
3899 void (*DdmConnection_start)(const char* name);
3900 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003901 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003902 if (!DdmConnection_start) {
3903 dlclose(libddmconnection_dso);
3904 return false;
3905 }
3906 (*DdmConnection_start)(getServiceName());
3907 return true;
3908}
3909
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003910status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003911 switch (code) {
3912 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003913 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003914 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003915 case CLEAR_ANIMATION_FRAME_STATS:
3916 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003917 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003918 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003919 {
3920 // codes that require permission check
3921 IPCThreadState* ipc = IPCThreadState::self();
3922 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003923 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003924 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003925 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003926 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003927 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003929 break;
3930 }
Robert Carr1db73f62016-12-21 12:58:51 -08003931 /*
3932 * Calling setTransactionState is safe, because you need to have been
3933 * granted a reference to Client* and Handle* to do anything with it.
3934 *
3935 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3936 */
3937 case SET_TRANSACTION_STATE:
3938 case CREATE_SCOPED_CONNECTION:
3939 {
3940 return OK;
3941 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003942 case CAPTURE_SCREEN:
3943 {
3944 // codes that require permission check
3945 IPCThreadState* ipc = IPCThreadState::self();
3946 const int pid = ipc->getCallingPid();
3947 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003948 if ((uid != AID_GRAPHICS) &&
3949 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003950 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003951 return PERMISSION_DENIED;
3952 }
3953 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003954 }
3955 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003956 return OK;
3957}
3958
3959status_t SurfaceFlinger::onTransact(
3960 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3961{
3962 status_t credentialCheck = CheckTransactCodeCredentials(code);
3963 if (credentialCheck != OK) {
3964 return credentialCheck;
3965 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003966
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003967 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3968 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003969 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003970 IPCThreadState* ipc = IPCThreadState::self();
3971 const int uid = ipc->getCallingUid();
3972 if (CC_UNLIKELY(uid != AID_SYSTEM
3973 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003974 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003975 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003976 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003977 return PERMISSION_DENIED;
3978 }
3979 int n;
3980 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003981 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003982 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003983 return NO_ERROR;
3984 case 1002: // SHOW_UPDATES
3985 n = data.readInt32();
3986 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003987 invalidateHwcGeometry();
3988 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003989 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003990 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003991 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003992 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003993 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003994 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003995 setTransactionFlags(
3996 eTransactionNeeded|
3997 eDisplayTransactionNeeded|
3998 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003999 return NO_ERROR;
4000 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004001 case 1006:{ // send empty update
4002 signalRefresh();
4003 return NO_ERROR;
4004 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004005 case 1008: // toggle use of hw composer
4006 n = data.readInt32();
4007 mDebugDisableHWC = n ? 1 : 0;
4008 invalidateHwcGeometry();
4009 repaintEverything();
4010 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004011 case 1009: // toggle use of transform hint
4012 n = data.readInt32();
4013 mDebugDisableTransformHint = n ? 1 : 0;
4014 invalidateHwcGeometry();
4015 repaintEverything();
4016 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004017 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004018 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004019 reply->writeInt32(0);
4020 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004021 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004022 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004023 return NO_ERROR;
4024 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004025 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004026 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004027 return NO_ERROR;
4028 }
4029 case 1014: {
4030 // daltonize
4031 n = data.readInt32();
4032 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004033 case 1:
4034 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4035 break;
4036 case 2:
4037 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4038 break;
4039 case 3:
4040 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4041 break;
4042 default:
4043 mDaltonizer.setType(ColorBlindnessType::None);
4044 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004045 }
4046 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004047 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004048 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004049 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004050 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004051 invalidateHwcGeometry();
4052 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004053 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004054 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004055 case 1015: {
4056 // apply a color matrix
4057 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004058 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004059 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004060 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004061 for (size_t j = 0; j < 4; j++) {
4062 mColorMatrix[i][j] = data.readFloat();
4063 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004064 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004065 } else {
4066 mColorMatrix = mat4();
4067 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004068
4069 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4070 // the division by w in the fragment shader
4071 float4 lastRow(transpose(mColorMatrix)[3]);
4072 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4073 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4074 }
4075
Alan Viverette9c5a3332013-09-12 20:04:35 -07004076 invalidateHwcGeometry();
4077 repaintEverything();
4078 return NO_ERROR;
4079 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004080 // This is an experimental interface
4081 // Needs to be shifted to proper binder interface when we productize
4082 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004083 n = data.readInt32();
4084 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004085 return NO_ERROR;
4086 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004087 case 1017: {
4088 n = data.readInt32();
4089 mForceFullDamage = static_cast<bool>(n);
4090 return NO_ERROR;
4091 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004092 case 1018: { // Modify Choreographer's phase offset
4093 n = data.readInt32();
4094 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4095 return NO_ERROR;
4096 }
4097 case 1019: { // Modify SurfaceFlinger's phase offset
4098 n = data.readInt32();
4099 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4100 return NO_ERROR;
4101 }
Irvel468051e2016-06-13 16:44:44 -07004102 case 1020: { // Layer updates interceptor
4103 n = data.readInt32();
4104 if (n) {
4105 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004106 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004107 }
4108 else{
4109 ALOGV("Interceptor disabled");
4110 mInterceptor.disable();
4111 }
4112 return NO_ERROR;
4113 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004114 case 1021: { // Disable HWC virtual displays
4115 n = data.readInt32();
4116 mUseHwcVirtualDisplays = !n;
4117 return NO_ERROR;
4118 }
Romain Guy0147a172017-06-01 13:53:56 -07004119 case 1022: { // Set saturation boost
4120 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4121
4122 invalidateHwcGeometry();
4123 repaintEverything();
4124 return NO_ERROR;
4125 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004126 }
4127 }
4128 return err;
4129}
4130
Mathias Agopian53331da2011-08-22 21:44:41 -07004131void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004132 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004133 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004134}
4135
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004136// Checks that the requested width and height are valid and updates them to the display dimensions
4137// if they are set to 0
4138static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4139 Transform::orientation_flags rotation,
4140 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4141 // get screen geometry
4142 uint32_t displayWidth = displayDevice->getWidth();
4143 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004144
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004145 if (rotation & Transform::ROT_90) {
4146 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004147 }
4148
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004149 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4150 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4151 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4152 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004153 }
4154
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004155 if (*requestedWidth == 0) {
4156 *requestedWidth = displayWidth;
4157 }
4158 if (*requestedHeight == 0) {
4159 *requestedHeight = displayHeight;
4160 }
4161
4162 return NO_ERROR;
4163}
4164
4165// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4166class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004167public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004168 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4169 ~WindowDisconnector() {
4170 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004171 }
4172
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004173private:
4174 ANativeWindow* mWindow;
4175 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004176};
4177
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004178static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4179 uint32_t requestedHeight, bool hasWideColorDisplay,
4180 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4181 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4182 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4183
4184 int err = 0;
4185 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4186 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4187 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4188 err |= native_window_set_usage(window, usage);
4189
4190 if (hasWideColorDisplay) {
4191 err |= native_window_set_buffers_data_space(window,
4192 renderEngineUsesWideColor
4193 ? HAL_DATASPACE_DISPLAY_P3
4194 : HAL_DATASPACE_V0_SRGB);
4195 }
4196
4197 if (err != NO_ERROR) {
4198 return BAD_VALUE;
4199 }
4200
4201 /* TODO: Once we have the sync framework everywhere this can use
4202 * server-side waits on the fence that dequeueBuffer returns.
4203 */
4204 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4205 if (err != NO_ERROR) {
4206 return err;
4207 }
4208
4209 return NO_ERROR;
4210}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004211
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004212status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4213 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004214 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004215 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004216 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004217 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004218
4219 if (CC_UNLIKELY(display == 0))
4220 return BAD_VALUE;
4221
4222 if (CC_UNLIKELY(producer == 0))
4223 return BAD_VALUE;
4224
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004225 // if we have secure windows on this display, never allow the screen capture
4226 // unless the producer interface is local (i.e.: we can take a screenshot for
4227 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004228 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004229
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004230 // Convert to surfaceflinger's internal rotation type.
4231 Transform::orientation_flags rotationFlags;
4232 switch (rotation) {
4233 case ISurfaceComposer::eRotateNone:
4234 rotationFlags = Transform::ROT_0;
4235 break;
4236 case ISurfaceComposer::eRotate90:
4237 rotationFlags = Transform::ROT_90;
4238 break;
4239 case ISurfaceComposer::eRotate180:
4240 rotationFlags = Transform::ROT_180;
4241 break;
4242 case ISurfaceComposer::eRotate270:
4243 rotationFlags = Transform::ROT_270;
4244 break;
4245 default:
4246 rotationFlags = Transform::ROT_0;
4247 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4248 break;
4249 }
4250
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004251 { // Autolock scope
4252 Mutex::Autolock lock(mStateLock);
4253 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4254 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004255 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004256
4257 // create a surface (because we're a producer, and we need to
4258 // dequeue/queue a buffer)
4259 sp<Surface> surface = new Surface(producer, false);
4260
4261 // Put the screenshot Surface into async mode so that
4262 // Layer::headFenceHasSignaled will always return true and we'll latch the
4263 // first buffer regardless of whether or not its acquire fence has
4264 // signaled. This is needed to avoid a race condition in the rotation
4265 // animation. See b/30209608
4266 surface->setAsyncMode(true);
4267
4268 ANativeWindow* window = surface.get();
4269
4270 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4271 if (result != NO_ERROR) {
4272 return result;
4273 }
4274 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4275
4276 ANativeWindowBuffer* buffer = nullptr;
4277 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4278 getRenderEngine().usesWideColor(), &buffer);
4279 if (result != NO_ERROR) {
4280 return result;
4281 }
4282
4283 // This mutex protects syncFd and captureResult for communication of the return values from the
4284 // main thread back to this Binder thread
4285 std::mutex captureMutex;
4286 std::condition_variable captureCondition;
4287 std::unique_lock<std::mutex> captureLock(captureMutex);
4288 int syncFd = -1;
4289 std::optional<status_t> captureResult;
4290
4291 sp<LambdaMessage> message = new LambdaMessage([&]() {
4292 // If there is a refresh pending, bug out early and tell the binder thread to try again
4293 // after the refresh.
4294 if (mRefreshPending) {
4295 ATRACE_NAME("Skipping screenshot for now");
4296 std::unique_lock<std::mutex> captureLock(captureMutex);
4297 captureResult = std::make_optional<status_t>(EAGAIN);
4298 captureCondition.notify_one();
4299 return;
4300 }
4301
4302 status_t result = NO_ERROR;
4303 int fd = -1;
4304 {
4305 Mutex::Autolock _l(mStateLock);
4306 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4307 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4308 minLayerZ, maxLayerZ, useIdentityTransform,
4309 rotationFlags, isLocalScreenshot, &fd);
4310 }
4311
4312 {
4313 std::unique_lock<std::mutex> captureLock(captureMutex);
4314 syncFd = fd;
4315 captureResult = std::make_optional<status_t>(result);
4316 captureCondition.notify_one();
4317 }
4318 });
4319
4320 result = postMessageAsync(message);
4321 if (result == NO_ERROR) {
4322 captureCondition.wait(captureLock, [&]() { return captureResult; });
4323 while (*captureResult == EAGAIN) {
4324 captureResult.reset();
4325 result = postMessageAsync(message);
4326 if (result != NO_ERROR) {
4327 return result;
4328 }
4329 captureCondition.wait(captureLock, [&]() { return captureResult; });
4330 }
4331 result = *captureResult;
4332 }
4333
4334 if (result == NO_ERROR) {
4335 // queueBuffer takes ownership of syncFd
4336 result = window->queueBuffer(window, buffer, syncFd);
4337 }
4338
4339 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004340}
4341
Mathias Agopian180f10d2013-04-10 22:55:41 -07004342
4343void SurfaceFlinger::renderScreenImplLocked(
4344 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004345 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004346 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004347 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004348{
4349 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004350 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004351
4352 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004353 const int32_t hw_w = hw->getWidth();
4354 const int32_t hw_h = hw->getHeight();
4355 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004356 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004357
Dan Stozac1879002014-05-22 15:59:05 -07004358 // if a default or invalid sourceCrop is passed in, set reasonable values
4359 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4360 !sourceCrop.isValid()) {
4361 sourceCrop.setLeftTop(Point(0, 0));
4362 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4363 }
4364
4365 // ensure that sourceCrop is inside screen
4366 if (sourceCrop.left < 0) {
4367 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4368 }
Dan Stozabe31f442014-06-11 11:20:54 -07004369 if (sourceCrop.right > hw_w) {
4370 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004371 }
4372 if (sourceCrop.top < 0) {
4373 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4374 }
Dan Stozabe31f442014-06-11 11:20:54 -07004375 if (sourceCrop.bottom > hw_h) {
4376 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004377 }
4378
Romain Guy88d37dd2017-05-26 17:57:05 -07004379#ifdef USE_HWC2
4380 engine.setWideColor(hw->getWideColorSupport());
4381 engine.setColorMode(hw->getActiveColorMode());
4382#endif
4383
Mathias Agopian180f10d2013-04-10 22:55:41 -07004384 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004385 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004386
4387 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004388 engine.setViewportAndProjection(
4389 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004390 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004391
4392 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004393 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004394
Robert Carr1f0a16a2016-10-24 16:27:39 -07004395 // We loop through the first level of layers without traversing,
4396 // as we need to interpret min/max layer Z in the top level Z space.
4397 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004398 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004399 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004400 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004401 const Layer::State& state(layer->getDrawingState());
4402 if (state.z < minLayerZ || state.z > maxLayerZ) {
4403 continue;
4404 }
Dan Stoza412903f2017-04-27 13:42:17 -07004405 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004406 if (!layer->isVisible()) {
4407 return;
4408 }
4409 if (filtering) layer->setFiltering(true);
4410 layer->draw(hw, useIdentityTransform);
4411 if (filtering) layer->setFiltering(false);
4412 });
4413 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004414
Mathias Agopian931bda12013-08-28 18:11:46 -07004415 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004416}
4417
Dan Stozaabcda352017-06-01 14:37:39 -07004418// A simple RAII class that holds an EGLImage and destroys it either:
4419// a) When the destroy() method is called
4420// b) When the object goes out of scope
4421class ImageHolder {
4422public:
4423 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4424 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004425
Dan Stozaabcda352017-06-01 14:37:39 -07004426 void destroy() {
4427 if (mImage != EGL_NO_IMAGE_KHR) {
4428 eglDestroyImageKHR(mDisplay, mImage);
4429 mImage = EGL_NO_IMAGE_KHR;
4430 }
4431 }
4432
4433private:
4434 const EGLDisplay mDisplay;
4435 EGLImageKHR mImage;
4436};
4437
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004438status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4439 ANativeWindowBuffer* buffer, Rect sourceCrop,
4440 uint32_t reqWidth, uint32_t reqHeight,
4441 int32_t minLayerZ, int32_t maxLayerZ,
4442 bool useIdentityTransform,
4443 Transform::orientation_flags rotation,
4444 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004445 ATRACE_CALL();
4446
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004447 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004448 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004449 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004450 if (layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004451 (state.z < minLayerZ || state.z > maxLayerZ)) {
4452 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004453 }
Dan Stoza412903f2017-04-27 13:42:17 -07004454 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004455 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4456 layer->isSecure());
4457 });
4458 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004459
4460 if (!isLocalScreenshot && secureLayerIsVisible) {
4461 ALOGW("FB is protected: PERMISSION_DENIED");
4462 return PERMISSION_DENIED;
4463 }
4464
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004465 int syncFd = -1;
4466 // create an EGLImage from the buffer so we can later
4467 // turn it into a texture
4468 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4469 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4470 if (image == EGL_NO_IMAGE_KHR) {
4471 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004472 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004473
Dan Stozaabcda352017-06-01 14:37:39 -07004474 // This will automatically destroy the image if we return before calling its destroy method
4475 ImageHolder imageHolder(mEGLDisplay, image);
4476
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004477 // this binds the given EGLImage as a framebuffer for the
4478 // duration of this scope.
4479 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004480 if (imageBond.getStatus() != NO_ERROR) {
4481 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004482 return INVALID_OPERATION;
4483 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004484
Dan Stozaabcda352017-06-01 14:37:39 -07004485 // this will in fact render into our dequeued buffer
4486 // via an FBO, which means we didn't have to create
4487 // an EGLSurface and therefore we're not
4488 // dependent on the context's EGLConfig.
4489 renderScreenImplLocked(
4490 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4491 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004492
Dan Stozaabcda352017-06-01 14:37:39 -07004493 // Attempt to create a sync khr object that can produce a sync point. If that
4494 // isn't available, create a non-dupable sync object in the fallback path and
4495 // wait on it directly.
4496 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4497 if (!DEBUG_SCREENSHOTS) {
4498 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4499 // native fence fd will not be populated until flush() is done.
4500 getRenderEngine().flush();
4501 }
4502
4503 if (sync != EGL_NO_SYNC_KHR) {
4504 // get the sync fd
4505 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4506 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4507 ALOGW("captureScreen: failed to dup sync khr object");
4508 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004509 }
Dan Stozaabcda352017-06-01 14:37:39 -07004510 eglDestroySyncKHR(mEGLDisplay, sync);
4511 } else {
4512 // fallback path
4513 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004514 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004515 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4516 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4517 EGLint eglErr = eglGetError();
4518 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4519 ALOGW("captureScreen: fence wait timed out");
4520 } else {
4521 ALOGW_IF(eglErr != EGL_SUCCESS,
4522 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004523 }
4524 eglDestroySyncKHR(mEGLDisplay, sync);
4525 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004526 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004527 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004528 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004529 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004530
4531 if (DEBUG_SCREENSHOTS) {
4532 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4533 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4534 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4535 hw, minLayerZ, maxLayerZ);
4536 delete [] pixels;
4537 }
4538
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004539 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004540 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004541
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004542 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004543}
4544
Mathias Agopiand5556842013-09-19 17:08:37 -07004545void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004546 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004547 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004548 for (size_t y=0 ; y<h ; y++) {
4549 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4550 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004551 if (p[x] != 0xFF000000) return;
4552 }
4553 }
4554 ALOGE("*** we just took a black screenshot ***\n"
4555 "requested minz=%d, maxz=%d, layerStack=%d",
4556 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004557
Robert Carr2047fae2016-11-28 14:09:09 -08004558 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004559 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004560 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004561 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004562 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004563 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004564 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4565 layer->isVisible() ? '+' : '-',
4566 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004567 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004568 i++;
4569 });
4570 }
4571 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004572 }
4573}
4574
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004575// ---------------------------------------------------------------------------
4576
Dan Stoza412903f2017-04-27 13:42:17 -07004577void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4578 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004579}
4580
Dan Stoza412903f2017-04-27 13:42:17 -07004581void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4582 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004583}
4584
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004585}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004586
4587
4588#if defined(__gl_h_)
4589#error "don't include gl/gl.h in this file"
4590#endif
4591
4592#if defined(__gl2_h_)
4593#error "don't include gl2/gl2.h in this file"
4594#endif