blob: 2d05d9c605362d15ff6f86a5924191c6ad1627bb [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>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080068#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070069#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070071#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080072#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070074#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Mathias Agopiana4912602012-07-12 14:25:33 -070079#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070080#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070081#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Mathias Agopianff2ed702013-09-01 21:36:12 -070083#include "Effects/Daltonizer.h"
84
Mathias Agopian875d8e12013-06-07 15:35:48 -070085#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070087
Jiyong Park4b20c2e2017-01-14 19:45:11 +090088#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090089#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091#define DISPLAY_COUNT 1
92
Mathias Agopianfee2b462013-07-03 12:34:01 -070093/*
94 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
95 * black pixels.
96 */
97#define DEBUG_SCREENSHOTS false
98
Mathias Agopianca088332013-03-28 17:44:13 -070099EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700102
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107// ---------------------------------------------------------------------------
108
Mathias Agopian99b49842011-06-27 16:05:52 -0700109const String16 sHardwareTest("android.permission.HARDWARE_TEST");
110const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
111const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
112const String16 sDump("android.permission.DUMP");
113
114// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800115int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
116int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700117bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700118int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700119bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800120uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800121bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800122bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800123int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600124bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700127 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700129 mTransactionPending(false),
130 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700131 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700132 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700133 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800134 mHwc(nullptr),
135 mRealHwc(nullptr),
136 mVrHwc(nullptr),
137 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800139 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800141 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800142 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700144 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700145 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700146 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700147 mDebugInSwapBuffers(0),
148 mLastSwapBufferTime(0),
149 mDebugInTransaction(0),
150 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700151 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700152 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800153 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000154 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700155 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700156 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700157 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800158 mHasPoweredOff(false),
159 mFrameBuckets(),
160 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700161 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800162 mNumLayers(0),
163 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800164{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800165 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800166
167 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
168 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
169
170 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
171 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
172
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800173 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
174 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700176 useContextPriority = getBool< ISurfaceFlingerConfigs,
177 &ISurfaceFlingerConfigs::useContextPriority>(false);
178
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700179 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
180 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
181
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700182 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
183 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
184
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800185 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
186 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
187
Steven Thomas050b2c82017-03-06 11:45:16 -0800188 // Vr flinger is only enabled on Daydream ready devices.
189 useVrFlinger = getBool< ISurfaceFlingerConfigs,
190 &ISurfaceFlingerConfigs::useVrFlinger>(false);
191
Fabien Sanglard1971b632017-03-10 14:50:03 -0800192 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
193 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
194
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600195 hasWideColorDisplay =
196 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
197
Saurabh Shahf4174532017-07-13 10:45:07 -0700198 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
199
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200 // debugging stuff...
201 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700202
Mathias Agopianb4b17302013-03-20 18:36:41 -0700203 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700204 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700205
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206 property_get("debug.sf.showupdates", value, "0");
207 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700208
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700209 property_get("debug.sf.ddms", value, "0");
210 mDebugDDMS = atoi(value);
211 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700212 if (!startDdmConnection()) {
213 // start failed, and DDMS debugging not enabled
214 mDebugDDMS = 0;
215 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700216 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700217 ALOGI_IF(mDebugRegion, "showupdates enabled");
218 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700219
220 property_get("debug.sf.disable_backpressure", value, "0");
221 mPropagateBackpressure = !atoi(value);
222 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700223
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800224 property_get("debug.sf.enable_hwc_vds", value, "0");
225 mUseHwcVirtualDisplays = atoi(value);
226 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800227
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800228 property_get("ro.sf.disable_triple_buffer", value, "1");
229 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800230 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700231
Romain Guy11d63f42017-07-20 12:47:14 -0700232 // We should be reading 'persist.sys.sf.color_saturation' here
233 // but since /data may be encrypted, we need to wait until after vold
234 // comes online to attempt to read the property. The property is
235 // instead read after the boot animation
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236}
237
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800238void SurfaceFlinger::onFirstRef()
239{
240 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800241}
242
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800243SurfaceFlinger::~SurfaceFlinger()
244{
Mathias Agopiana4912602012-07-12 14:25:33 -0700245 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
246 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
247 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800248}
249
Dan Stozac7014012014-02-14 15:03:43 -0800250void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800251{
252 // the window manager died on us. prepare its eulogy.
253
Andy McFadden13a082e2012-08-24 10:16:42 -0700254 // restore initial conditions (default device unblank, etc)
255 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800256
257 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700258 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800259}
260
Robert Carr1db73f62016-12-21 12:58:51 -0800261static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700262 status_t err = client->initCheck();
263 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800264 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265 }
Robert Carr1db73f62016-12-21 12:58:51 -0800266 return nullptr;
267}
268
269sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
270 return initClient(new Client(this));
271}
272
273sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
274 const sp<IGraphicBufferProducer>& gbp) {
275 if (authenticateSurfaceTexture(gbp) == false) {
276 return nullptr;
277 }
278 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
279 if (layer == nullptr) {
280 return nullptr;
281 }
282
283 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284}
285
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700286sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
287 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700288{
289 class DisplayToken : public BBinder {
290 sp<SurfaceFlinger> flinger;
291 virtual ~DisplayToken() {
292 // no more references, this display must be terminated
293 Mutex::Autolock _l(flinger->mStateLock);
294 flinger->mCurrentState.displays.removeItem(this);
295 flinger->setTransactionFlags(eDisplayTransactionNeeded);
296 }
297 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700298 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700299 : flinger(flinger) {
300 }
301 };
302
303 sp<BBinder> token = new DisplayToken(this);
304
305 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700306 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700307 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700308 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700309 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700310 return token;
311}
312
Jesse Hall6c913be2013-08-08 12:15:49 -0700313void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
314 Mutex::Autolock _l(mStateLock);
315
316 ssize_t idx = mCurrentState.displays.indexOfKey(display);
317 if (idx < 0) {
318 ALOGW("destroyDisplay: invalid display token");
319 return;
320 }
321
322 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
323 if (!info.isVirtualDisplay()) {
324 ALOGE("destroyDisplay called for non-virtual display");
325 return;
326 }
Irvelffc9efc2016-07-27 15:16:37 -0700327 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700328 mCurrentState.displays.removeItemsAt(idx);
329 setTransactionFlags(eDisplayTransactionNeeded);
330}
331
Jesse Hall692c7232012-11-08 15:41:56 -0800332void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800333 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800334 ALOGW_IF(mBuiltinDisplays[type],
335 "Overwriting display token for display type %d", type);
336 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800337 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700338 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800339 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700340 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800341}
342
Mathias Agopiane57f2922012-08-09 16:29:12 -0700343sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700344 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700345 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
346 return NULL;
347 }
Jesse Hall692c7232012-11-08 15:41:56 -0800348 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700349}
350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351void SurfaceFlinger::bootFinished()
352{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700353 if (mStartPropertySetThread->join() != NO_ERROR) {
354 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800355 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800356 const nsecs_t now = systemTime();
357 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000358 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700359
360 // wait patiently for the window manager death
361 const String16 name("window");
362 sp<IBinder> window(defaultServiceManager()->getService(name));
363 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700364 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700365 }
366
Steven Thomas050b2c82017-03-06 11:45:16 -0800367 if (mVrFlinger) {
368 mVrFlinger->OnBootFinished();
369 }
370
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700371 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700372 // formerly we would just kill the process, but we now ask it to exit so it
373 // can choose where to stop the animation.
374 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700375
376 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
377 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
378 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700379
Romain Guyc53d3552017-07-20 18:49:46 -0700380 sp<LambdaMessage> bootFinished = new LambdaMessage([&]() {
381 mBootFinished = true;
382
Romain Guy11d63f42017-07-20 12:47:14 -0700383 readPersistentProperties();
Romain Guyc53d3552017-07-20 18:49:46 -0700384
385#ifdef USE_HWC2
386 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
387 if (hw->getWideColorSupport()) {
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -0600388 hw->setCompositionDataSpace(HAL_DATASPACE_V0_SRGB);
Romain Guyc53d3552017-07-20 18:49:46 -0700389 setActiveColorModeInternal(hw, HAL_COLOR_MODE_SRGB);
390 }
391#endif
Romain Guy11d63f42017-07-20 12:47:14 -0700392 });
Romain Guyc53d3552017-07-20 18:49:46 -0700393 postMessageAsync(bootFinished);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800394}
395
Mathias Agopian3f844832013-08-07 21:24:32 -0700396void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700397 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700398 RenderEngine& engine;
399 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700400 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700401 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
402 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700403 }
404 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700405 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700406 return true;
407 }
408 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700409 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700410}
411
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412class DispSyncSource : public VSyncSource, private DispSync::Callback {
413public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700414 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000415 const char* name) :
416 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700417 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700418 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000419 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
420 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700421 mDispSync(dispSync),
422 mCallbackMutex(),
423 mCallback(),
424 mVsyncMutex(),
425 mPhaseOffset(phaseOffset),
426 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700427
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700428 virtual ~DispSyncSource() {}
429
430 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700431 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000433 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 static_cast<DispSync::Callback*>(this));
435 if (err != NO_ERROR) {
436 ALOGE("error registering vsync callback: %s (%d)",
437 strerror(-err), err);
438 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700439 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700440 } else {
441 status_t err = mDispSync->removeEventListener(
442 static_cast<DispSync::Callback*>(this));
443 if (err != NO_ERROR) {
444 ALOGE("error unregistering vsync callback: %s (%d)",
445 strerror(-err), err);
446 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700447 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700448 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700449 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700450 }
451
452 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700453 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454 mCallback = callback;
455 }
456
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700457 virtual void setPhaseOffset(nsecs_t phaseOffset) {
458 Mutex::Autolock lock(mVsyncMutex);
459
460 // Normalize phaseOffset to [0, period)
461 auto period = mDispSync->getPeriod();
462 phaseOffset %= period;
463 if (phaseOffset < 0) {
464 // If we're here, then phaseOffset is in (-period, 0). After this
465 // operation, it will be in (0, period)
466 phaseOffset += period;
467 }
468 mPhaseOffset = phaseOffset;
469
470 // If we're not enabled, we don't need to mess with the listeners
471 if (!mEnabled) {
472 return;
473 }
474
475 // Remove the listener with the old offset
476 status_t err = mDispSync->removeEventListener(
477 static_cast<DispSync::Callback*>(this));
478 if (err != NO_ERROR) {
479 ALOGE("error unregistering vsync callback: %s (%d)",
480 strerror(-err), err);
481 }
482
483 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000484 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700485 static_cast<DispSync::Callback*>(this));
486 if (err != NO_ERROR) {
487 ALOGE("error registering vsync callback: %s (%d)",
488 strerror(-err), err);
489 }
490 }
491
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700492private:
493 virtual void onDispSyncEvent(nsecs_t when) {
494 sp<VSyncSource::Callback> callback;
495 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700496 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700497 callback = mCallback;
498
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700499 if (mTraceVsync) {
500 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700501 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700502 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700503 }
504
505 if (callback != NULL) {
506 callback->onVSyncEvent(when);
507 }
508 }
509
Tim Murray4a4e4a22016-04-19 16:29:23 +0000510 const char* const mName;
511
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512 int mValue;
513
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700514 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700515 const String8 mVsyncOnLabel;
516 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700517
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700519
520 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700521 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700522
523 Mutex mVsyncMutex; // Protects the following
524 nsecs_t mPhaseOffset;
525 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700526};
527
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700528class InjectVSyncSource : public VSyncSource {
529public:
530 InjectVSyncSource() {}
531
532 virtual ~InjectVSyncSource() {}
533
534 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
535 std::lock_guard<std::mutex> lock(mCallbackMutex);
536 mCallback = callback;
537 }
538
539 virtual void onInjectSyncEvent(nsecs_t when) {
540 std::lock_guard<std::mutex> lock(mCallbackMutex);
541 mCallback->onVSyncEvent(when);
542 }
543
544 virtual void setVSyncEnabled(bool) {}
545 virtual void setPhaseOffset(nsecs_t) {}
546
547private:
548 std::mutex mCallbackMutex; // Protects the following
549 sp<VSyncSource::Callback> mCallback;
550};
551
Wei Wangf9b05ee2017-07-19 20:59:39 -0700552// Do not call property_set on main thread which will be blocked by init
553// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700554void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700555 ALOGI( "SurfaceFlinger's main thread ready to run. "
556 "Initializing graphics H/W...");
557
Romain Guyc53d3552017-07-20 18:49:46 -0700558 ALOGI("Phase offset NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900559
Dan Stoza9e56aa02015-11-02 13:00:03 -0800560 { // Autolock scope
561 Mutex::Autolock _l(mStateLock);
562
563 // initialize EGL for the default display
564 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
565 eglInitialize(mEGLDisplay, NULL, NULL);
566
567 // start the EventThread
568 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
569 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700570 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800571 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
572 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700573 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800574 mEventQueue.setEventThread(mSFEventThread);
575
Tim Murray22752852017-05-04 13:38:49 -0700576 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700577 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700578 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700579 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
580 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
581 }
Tim Murray22752852017-05-04 13:38:49 -0700582 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
583 ALOGE("Couldn't set SCHED_FIFO for EventThread");
584 }
Tim Murray41a38532016-06-22 12:42:10 -0700585
Dan Stoza9e56aa02015-11-02 13:00:03 -0800586 // Get a RenderEngine for the given display / config (can't fail)
587 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700588 HAL_PIXEL_FORMAT_RGBA_8888,
589 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800590 }
591
592 // Drop the state lock while we initialize the hardware composer. We drop
593 // the lock because on creation, it will call back into SurfaceFlinger to
594 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800595 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
596 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800597 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800598 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800599 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
600
Jesse Hall692c7232012-11-08 15:41:56 -0800601 Mutex::Autolock _l(mStateLock);
602
Steven Thomas050b2c82017-03-06 11:45:16 -0800603 if (useVrFlinger) {
604 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700605 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800606 mVrFlingerRequestsDisplay = requestDisplay;
607 signalTransaction();
608 };
609 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
610 vrFlingerRequestDisplayCallback);
611 if (!mVrFlinger) {
612 ALOGE("Failed to start vrflinger");
613 }
614 }
615
Mathias Agopian875d8e12013-06-07 15:35:48 -0700616 // retrieve the EGL context that was selected/created
617 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700618
Mathias Agopianda27af92012-09-13 18:17:13 -0700619 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
620 "couldn't create EGLContext");
621
Dan Stoza9e56aa02015-11-02 13:00:03 -0800622 // make the GLContext current so that we can create textures when creating
623 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700624 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700625
Jamie Gennisd1700752013-10-14 12:22:52 -0700626 mEventControlThread = new EventControlThread(this);
627 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
628
Mathias Agopian92a979a2012-08-02 18:32:23 -0700629 // initialize our drawing state
630 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700631
Andy McFadden13a082e2012-08-24 10:16:42 -0700632 // set initial conditions (e.g. unblank default device)
633 initializeDisplays();
634
Dan Stoza4e637772016-07-28 13:31:51 -0700635 mRenderEngine->primeCache();
636
Wei Wangf9b05ee2017-07-19 20:59:39 -0700637 // Inform native graphics APIs whether the present timestamp is supported:
638 if (getHwComposer().hasCapability(
639 HWC2::Capability::PresentFenceIsNotReliable)) {
640 mStartPropertySetThread = new StartPropertySetThread(false);
641 } else {
642 mStartPropertySetThread = new StartPropertySetThread(true);
643 }
644
645 if (mStartPropertySetThread->Start() != NO_ERROR) {
646 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800647 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800648
Dan Stoza9e56aa02015-11-02 13:00:03 -0800649 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700650}
651
Romain Guy11d63f42017-07-20 12:47:14 -0700652void SurfaceFlinger::readPersistentProperties() {
653 char value[PROPERTY_VALUE_MAX];
654
655 property_get("persist.sys.sf.color_saturation", value, "1.0");
656 mSaturation = atof(value);
657 ALOGV("Saturation is set to %.2f", mSaturation);
658}
659
Mathias Agopiana67e4182012-06-19 17:26:12 -0700660void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800661 // Start boot animation service by setting a property mailbox
662 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700663 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800664 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700665 if (mStartPropertySetThread->join() != NO_ERROR) {
666 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800667 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700668}
669
Mathias Agopian875d8e12013-06-07 15:35:48 -0700670size_t SurfaceFlinger::getMaxTextureSize() const {
671 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700672}
673
Mathias Agopian875d8e12013-06-07 15:35:48 -0700674size_t SurfaceFlinger::getMaxViewportDims() const {
675 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700676}
677
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800678// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800679
Jamie Gennis582270d2011-08-17 18:19:00 -0700680bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800681 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800682 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800683 return authenticateSurfaceTextureLocked(bufferProducer);
684}
685
686bool SurfaceFlinger::authenticateSurfaceTextureLocked(
687 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800688 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700689 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800690}
691
Brian Anderson6b376712017-04-04 10:51:39 -0700692status_t SurfaceFlinger::getSupportedFrameTimestamps(
693 std::vector<FrameEvent>* outSupported) const {
694 *outSupported = {
695 FrameEvent::REQUESTED_PRESENT,
696 FrameEvent::ACQUIRE,
697 FrameEvent::LATCH,
698 FrameEvent::FIRST_REFRESH_START,
699 FrameEvent::LAST_REFRESH_START,
700 FrameEvent::GPU_COMPOSITION_DONE,
701 FrameEvent::DEQUEUE_READY,
702 FrameEvent::RELEASE,
703 };
704 if (!getHwComposer().hasCapability(
705 HWC2::Capability::PresentFenceIsNotReliable)) {
706 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
707 }
708 return NO_ERROR;
709}
710
Dan Stoza7f7da322014-05-02 15:26:25 -0700711status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
712 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700713 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700714 return BAD_VALUE;
715 }
716
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500717 if (!display.get())
718 return NAME_NOT_FOUND;
719
Jesse Hall692c7232012-11-08 15:41:56 -0800720 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700721 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800722 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700723 type = i;
724 break;
725 }
726 }
727
728 if (type < 0) {
729 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700730 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700731
Mathias Agopian8b736f12012-08-13 17:54:26 -0700732 // TODO: Not sure if display density should handled by SF any longer
733 class Density {
734 static int getDensityFromProperty(char const* propName) {
735 char property[PROPERTY_VALUE_MAX];
736 int density = 0;
737 if (property_get(propName, property, NULL) > 0) {
738 density = atoi(property);
739 }
740 return density;
741 }
742 public:
743 static int getEmuDensity() {
744 return getDensityFromProperty("qemu.sf.lcd_density"); }
745 static int getBuildDensity() {
746 return getDensityFromProperty("ro.sf.lcd_density"); }
747 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700748
Dan Stoza7f7da322014-05-02 15:26:25 -0700749 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700750
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700752 DisplayInfo info = DisplayInfo();
753
Dan Stoza9e56aa02015-11-02 13:00:03 -0800754 float xdpi = hwConfig->getDpiX();
755 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700756
757 if (type == DisplayDevice::DISPLAY_PRIMARY) {
758 // The density of the device is provided by a build property
759 float density = Density::getBuildDensity() / 160.0f;
760 if (density == 0) {
761 // the build doesn't provide a density -- this is wrong!
762 // use xdpi instead
763 ALOGE("ro.sf.lcd_density must be defined as a build property");
764 density = xdpi / 160.0f;
765 }
766 if (Density::getEmuDensity()) {
767 // if "qemu.sf.lcd_density" is specified, it overrides everything
768 xdpi = ydpi = density = Density::getEmuDensity();
769 density /= 160.0f;
770 }
771 info.density = density;
772
773 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000774 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
775 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700776 } else {
777 // TODO: where should this value come from?
778 static const int TV_DENSITY = 213;
779 info.density = TV_DENSITY / 160.0f;
780 info.orientation = 0;
781 }
782
Dan Stoza9e56aa02015-11-02 13:00:03 -0800783 info.w = hwConfig->getWidth();
784 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700785 info.xdpi = xdpi;
786 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800787 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900788 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800789
Andy McFadden91b2ca82014-06-13 14:04:23 -0700790 // This is how far in advance a buffer must be queued for
791 // presentation at a given time. If you want a buffer to appear
792 // on the screen at time N, you must submit the buffer before
793 // (N - presentationDeadline).
794 //
795 // Normally it's one full refresh period (to give SF a chance to
796 // latch the buffer), but this can be reduced by configuring a
797 // DispSync offset. Any additional delays introduced by the hardware
798 // composer or panel must be accounted for here.
799 //
800 // We add an additional 1ms to allow for processing time and
801 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800802 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800803 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700804
805 // All non-virtual displays are currently considered secure.
806 info.secure = true;
807
Michael Wright28f24d02016-07-12 13:30:53 -0700808 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809 }
810
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 return NO_ERROR;
812}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700813
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800814status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700815 DisplayStatInfo* stats) {
816 if (stats == NULL) {
817 return BAD_VALUE;
818 }
819
820 // FIXME for now we always return stats for the primary display
821 memset(stats, 0, sizeof(*stats));
822 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
823 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
824 return NO_ERROR;
825}
826
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700827int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800828 if (display == NULL) {
829 ALOGE("%s : display is NULL", __func__);
830 return BAD_VALUE;
831 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700832
833 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700834 if (device != NULL) {
835 return device->getActiveConfig();
836 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700837
Dan Stoza24a42e92015-03-09 10:04:11 -0700838 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700839}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700840
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700841void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
842 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
843 this);
844 int32_t type = hw->getDisplayType();
845 int currentMode = hw->getActiveConfig();
846
847 if (mode == currentMode) {
848 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
849 return;
850 }
851
852 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
853 ALOGW("Trying to set config for virtual display");
854 return;
855 }
856
857 hw->setActiveConfig(mode);
858 getHwComposer().setActiveConfig(type, mode);
859}
860
861status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
862 class MessageSetActiveConfig: public MessageBase {
863 SurfaceFlinger& mFlinger;
864 sp<IBinder> mDisplay;
865 int mMode;
866 public:
867 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
868 int mode) :
869 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
870 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700871 Vector<DisplayInfo> configs;
872 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700873 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700874 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700875 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700876 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700877 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700878 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
879 if (hw == NULL) {
880 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700881 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700882 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
883 ALOGW("Attempt to set active config = %d for virtual display",
884 mMode);
885 } else {
886 mFlinger.setActiveConfigInternal(hw, mMode);
887 }
888 return true;
889 }
890 };
891 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
892 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700893 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700894}
Michael Wright28f24d02016-07-12 13:30:53 -0700895status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
896 Vector<android_color_mode_t>* outColorModes) {
897 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
898 return BAD_VALUE;
899 }
900
901 if (!display.get()) {
902 return NAME_NOT_FOUND;
903 }
904
905 int32_t type = NAME_NOT_FOUND;
906 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
907 if (display == mBuiltinDisplays[i]) {
908 type = i;
909 break;
910 }
911 }
912
913 if (type < 0) {
914 return type;
915 }
916
917 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
918 outColorModes->clear();
919 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
920
921 return NO_ERROR;
922}
923
924android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700925 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700926 if (device != nullptr) {
927 return device->getActiveColorMode();
928 }
929 return static_cast<android_color_mode_t>(BAD_VALUE);
930}
931
932void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
933 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700934 int32_t type = hw->getDisplayType();
935 android_color_mode_t currentMode = hw->getActiveColorMode();
936
937 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700938 return;
939 }
940
941 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
942 ALOGW("Trying to set config for virtual display");
943 return;
944 }
945
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600946 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
947 hw->getDisplayType());
948
Michael Wright28f24d02016-07-12 13:30:53 -0700949 hw->setActiveColorMode(mode);
950 getHwComposer().setActiveColorMode(type, mode);
951}
952
953
954status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
955 android_color_mode_t colorMode) {
956 class MessageSetActiveColorMode: public MessageBase {
957 SurfaceFlinger& mFlinger;
958 sp<IBinder> mDisplay;
959 android_color_mode_t mMode;
960 public:
961 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
962 android_color_mode_t mode) :
963 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
964 virtual bool handler() {
965 Vector<android_color_mode_t> modes;
966 mFlinger.getDisplayColorModes(mDisplay, &modes);
967 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
968 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600969 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
970 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700971 return true;
972 }
973 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
974 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600975 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
976 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700977 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600978 ALOGW("Attempt to set active color mode %s %d for virtual display",
979 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700980 } else {
981 mFlinger.setActiveColorModeInternal(hw, mMode);
982 }
983 return true;
984 }
985 };
986 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
987 postMessageSync(msg);
988 return NO_ERROR;
989}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700990
Svetoslavd85084b2014-03-20 10:28:31 -0700991status_t SurfaceFlinger::clearAnimationFrameStats() {
992 Mutex::Autolock _l(mStateLock);
993 mAnimFrameTracker.clearStats();
994 return NO_ERROR;
995}
996
997status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
998 Mutex::Autolock _l(mStateLock);
999 mAnimFrameTracker.getStats(outStats);
1000 return NO_ERROR;
1001}
1002
Dan Stozac4f471e2016-03-24 09:31:08 -07001003status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1004 HdrCapabilities* outCapabilities) const {
1005 Mutex::Autolock _l(mStateLock);
1006
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001007 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001008 if (displayDevice == nullptr) {
1009 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1010 return BAD_VALUE;
1011 }
1012
1013 std::unique_ptr<HdrCapabilities> capabilities =
1014 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1015 if (capabilities) {
1016 std::swap(*outCapabilities, *capabilities);
1017 } else {
1018 return BAD_VALUE;
1019 }
1020
1021 return NO_ERROR;
1022}
1023
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001024status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1025 if (enable == mInjectVSyncs) {
1026 return NO_ERROR;
1027 }
1028
1029 if (enable) {
1030 mInjectVSyncs = enable;
1031 ALOGV("VSync Injections enabled");
1032 if (mVSyncInjector.get() == nullptr) {
1033 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001034 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001035 }
1036 mEventQueue.setEventThread(mInjectorEventThread);
1037 } else {
1038 mInjectVSyncs = enable;
1039 ALOGV("VSync Injections disabled");
1040 mEventQueue.setEventThread(mSFEventThread);
1041 mVSyncInjector.clear();
1042 }
1043 return NO_ERROR;
1044}
1045
1046status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1047 if (!mInjectVSyncs) {
1048 ALOGE("VSync Injections not enabled");
1049 return BAD_VALUE;
1050 }
1051 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1052 ALOGV("Injecting VSync inside SurfaceFlinger");
1053 mVSyncInjector->onInjectSyncEvent(when);
1054 }
1055 return NO_ERROR;
1056}
1057
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001058// ----------------------------------------------------------------------------
1059
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001060sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1061 ISurfaceComposer::VsyncSource vsyncSource) {
1062 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1063 return mSFEventThread->createEventConnection();
1064 } else {
1065 return mEventThread->createEventConnection();
1066 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001067}
1068
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001069// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001070
1071void SurfaceFlinger::waitForEvent() {
1072 mEventQueue.waitMessage();
1073}
1074
1075void SurfaceFlinger::signalTransaction() {
1076 mEventQueue.invalidate();
1077}
1078
1079void SurfaceFlinger::signalLayerUpdate() {
1080 mEventQueue.invalidate();
1081}
1082
1083void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001084 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001085 mEventQueue.refresh();
1086}
1087
1088status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001089 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001090 return mEventQueue.postMessage(msg, reltime);
1091}
1092
1093status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001094 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001095 status_t res = mEventQueue.postMessage(msg, reltime);
1096 if (res == NO_ERROR) {
1097 msg->wait();
1098 }
1099 return res;
1100}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001101
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001102void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001103 do {
1104 waitForEvent();
1105 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001106}
1107
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001108void SurfaceFlinger::enableHardwareVsync() {
1109 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001110 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001111 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001112 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1113 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001114 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001115 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001116}
1117
Jesse Hall948fe0c2013-10-14 12:56:09 -07001118void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001119 Mutex::Autolock _l(mHWVsyncLock);
1120
Jesse Hall948fe0c2013-10-14 12:56:09 -07001121 if (makeAvailable) {
1122 mHWVsyncAvailable = true;
1123 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001124 // Hardware vsync is not currently available, so abort the resync
1125 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001126 return;
1127 }
1128
Dan Stoza9e56aa02015-11-02 13:00:03 -08001129 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1130 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001131
1132 mPrimaryDispSync.reset();
1133 mPrimaryDispSync.setPeriod(period);
1134
1135 if (!mPrimaryHWVsyncEnabled) {
1136 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001137 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1138 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001139 mPrimaryHWVsyncEnabled = true;
1140 }
1141}
1142
Jesse Hall948fe0c2013-10-14 12:56:09 -07001143void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001144 Mutex::Autolock _l(mHWVsyncLock);
1145 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001146 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1147 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001148 mPrimaryDispSync.endResync();
1149 mPrimaryHWVsyncEnabled = false;
1150 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001151 if (makeUnavailable) {
1152 mHWVsyncAvailable = false;
1153 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001154}
1155
Tim Murray4a4e4a22016-04-19 16:29:23 +00001156void SurfaceFlinger::resyncWithRateLimit() {
1157 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001158
1159 // No explicit locking is needed here since EventThread holds a lock while calling this method
1160 static nsecs_t sLastResyncAttempted = 0;
1161 const nsecs_t now = systemTime();
1162 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001163 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001164 }
Dan Stoza57164302017-05-08 14:03:54 -07001165 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001166}
1167
Steven Thomas3cfac282017-02-06 12:29:30 -08001168void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1169 nsecs_t timestamp) {
1170 Mutex::Autolock lock(mStateLock);
1171 // Ignore any vsyncs from the non-active hardware composer.
1172 if (composer != mHwc) {
1173 return;
1174 }
1175
Jamie Gennisd1700752013-10-14 12:22:52 -07001176 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001177
Jamie Gennisd1700752013-10-14 12:22:52 -07001178 { // Scope for the lock
1179 Mutex::Autolock _l(mHWVsyncLock);
1180 if (type == 0 && mPrimaryHWVsyncEnabled) {
1181 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001182 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001183 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001184
1185 if (needsHwVsync) {
1186 enableHardwareVsync();
1187 } else {
1188 disableHardwareVsync(false);
1189 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001190}
1191
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001192void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001193 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001194 *compositorTiming = mCompositorTiming;
1195}
1196
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001197void SurfaceFlinger::createDefaultDisplayDevice() {
1198 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1199 wp<IBinder> token = mBuiltinDisplays[type];
1200
1201 // All non-virtual displays are currently considered secure.
1202 const bool isSecure = true;
1203
1204 sp<IGraphicBufferProducer> producer;
1205 sp<IGraphicBufferConsumer> consumer;
1206 BufferQueue::createBufferQueue(&producer, &consumer);
1207
1208 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1209
1210 bool hasWideColorModes = false;
1211 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1212 for (android_color_mode_t colorMode : modes) {
1213 switch (colorMode) {
1214 case HAL_COLOR_MODE_DISPLAY_P3:
1215 case HAL_COLOR_MODE_ADOBE_RGB:
1216 case HAL_COLOR_MODE_DCI_P3:
1217 hasWideColorModes = true;
1218 break;
1219 default:
1220 break;
1221 }
1222 }
1223 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1224 token, fbs, producer, mRenderEngine->getEGLConfig(),
1225 hasWideColorModes && hasWideColorDisplay);
1226 mDisplays.add(token, hw);
Romain Guyc53d3552017-07-20 18:49:46 -07001227 setActiveColorModeInternal(hw, HAL_COLOR_MODE_NATIVE);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001228 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001229}
1230
1231void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001232 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001233
1234 if (composer->isUsingVrComposer()) {
1235 // We handle initializing the primary display device for the VR
1236 // window manager hwc explicitly at the time of transition.
1237 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1238 ALOGE("External displays are not supported by the vr hardware composer.");
1239 }
1240 return;
1241 }
1242
Dan Stoza9e56aa02015-11-02 13:00:03 -08001243 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1244 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001245 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1246 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001247 } else {
1248 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001249 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001250 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001251 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001252 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001253 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1254 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001255 }
1256 setTransactionFlags(eDisplayTransactionNeeded);
1257
Andy McFadden9e9689c2012-10-10 18:17:51 -07001258 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001259 }
Mathias Agopian86303202012-07-24 22:46:10 -07001260}
1261
Steven Thomas3cfac282017-02-06 12:29:30 -08001262void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1263 Mutex::Autolock lock(mStateLock);
1264 if (composer == mHwc) {
1265 repaintEverything();
1266 } else {
1267 // This isn't from our current hardware composer. If it's a callback
1268 // from the real composer, forward the refresh request to vr
1269 // flinger. Otherwise ignore it.
1270 if (!composer->isUsingVrComposer()) {
1271 mVrFlinger->OnHardwareComposerRefresh();
1272 }
1273 }
1274}
1275
Dan Stoza9e56aa02015-11-02 13:00:03 -08001276void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001278 getHwComposer().setVsyncEnabled(disp,
1279 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001280}
1281
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001282// Note: it is assumed the caller holds |mStateLock| when this is called
1283void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001284 disableHardwareVsync(true);
1285 clearHwcLayers(mDrawingState.layersSortedByZ);
1286 clearHwcLayers(mCurrentState.layersSortedByZ);
Steven Thomasf5a5f6e2017-07-17 13:59:23 -07001287 for (size_t disp = 0; disp < mDisplays.size(); ++disp) {
1288 clearHwcLayers(mDisplays[disp]->getVisibleLayersSortedByZ());
1289 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001290 // Clear the drawing state so that the logic inside of
1291 // handleTransactionLocked will fire. It will determine the delta between
1292 // mCurrentState and mDrawingState and re-apply all changes when we make the
1293 // transition.
1294 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001295 // Release virtual display hwcId during vr mode transition.
1296 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1297 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1298 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1299 displayDevice->disconnect(getHwComposer());
1300 }
1301 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001302 mDisplays.clear();
1303}
1304
Steven Thomas050b2c82017-03-06 11:45:16 -08001305void SurfaceFlinger::updateVrFlinger() {
1306 if (!mVrFlinger)
1307 return;
1308 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1309 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001310 return;
1311 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001312
Steven Thomas050b2c82017-03-06 11:45:16 -08001313 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001314 // Construct new HWComposer without holding any locks.
1315 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001316
1317 // Set up the event handlers. This step is neccessary to initialize the internal state of
1318 // the hardware composer object properly. Our callbacks are designed such that if they are
1319 // triggered between now and the point where the display is properly re-initialized, they
1320 // will not have any effect, so this is safe to do here, before the lock is aquired.
1321 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001322 ALOGV("Vr HWC created");
1323 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001324
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001325 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001326
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001327 if (vrFlingerRequestsDisplay) {
1328 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001329
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001330 mHwc = mVrHwc;
1331 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001332
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001333 } else {
1334 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001335
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001336 resetHwcLocked();
1337
1338 mHwc = mRealHwc;
1339 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001340 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001341
1342 mVisibleRegionsDirty = true;
1343 invalidateHwcGeometry();
1344
1345 // Explicitly re-initialize the primary display. This is because some other
1346 // parts of this class rely on the primary display always being available.
1347 createDefaultDisplayDevice();
1348
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001349 // Re-enable default display.
1350 sp<LambdaMessage> requestMessage = new LambdaMessage([&]() {
1351 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1352 setPowerModeInternal(hw, HWC_POWER_MODE_NORMAL);
1353
1354 // Reset the timing values to account for the period of the swapped in HWC
1355 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1356 const nsecs_t period = activeConfig->getVsyncPeriod();
1357 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1358
1359 // Use phase of 0 since phase is not known.
1360 // Use latency of 0, which will snap to the ideal latency.
1361 setCompositorTimingSnapped(0, period, 0);
1362 });
1363 postMessageAsync(requestMessage);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001364
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001365 android_atomic_or(1, &mRepaintEverything);
1366 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001367}
1368
Mathias Agopian4fec8732012-06-29 14:12:52 -07001369void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001370 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001371 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001372 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001373 bool frameMissed = !mHadClientComposition &&
1374 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001375 (mPreviousPresentFence->getSignalTime() ==
1376 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001377 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001378 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001379 signalLayerUpdate();
1380 break;
1381 }
1382
Steven Thomas050b2c82017-03-06 11:45:16 -08001383 // Now that we're going to make it to the handleMessageTransaction()
1384 // call below it's safe to call updateVrFlinger(), which will
1385 // potentially trigger a display handoff.
1386 updateVrFlinger();
1387
Dan Stoza6b9454d2014-11-07 16:00:59 -08001388 bool refreshNeeded = handleMessageTransaction();
1389 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001390 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001391 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001392 // Signal a refresh if a transaction modified the window state,
1393 // a new buffer was latched, or if HWC has requested a full
1394 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001395 signalRefresh();
1396 }
1397 break;
1398 }
1399 case MessageQueue::REFRESH: {
1400 handleMessageRefresh();
1401 break;
1402 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001403 }
1404}
1405
Dan Stoza6b9454d2014-11-07 16:00:59 -08001406bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001407 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001408 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001409 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001410 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001411 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001412 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001413}
1414
Dan Stoza6b9454d2014-11-07 16:00:59 -08001415bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001416 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001417 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001418}
1419
1420void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001421 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001422
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001423 mRefreshPending = false;
1424
Pablo Ceballos40845df2016-01-25 17:41:15 -08001425 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001426
Brian Andersond6927fb2016-07-23 23:37:30 -07001427 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001428 rebuildLayerStacks();
1429 setUpHWComposer();
1430 doDebugFlashRegions();
1431 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001432 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001433
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001434 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001435
1436 mHadClientComposition = false;
1437 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1438 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1439 mHadClientComposition = mHadClientComposition ||
1440 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1441 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001442
Dan Stoza9e56aa02015-11-02 13:00:03 -08001443 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001444}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001445
Mathias Agopiancd60f992012-08-16 16:28:27 -07001446void SurfaceFlinger::doDebugFlashRegions()
1447{
1448 // is debugging enabled
1449 if (CC_LIKELY(!mDebugRegion))
1450 return;
1451
1452 const bool repaintEverything = mRepaintEverything;
1453 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1454 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001455 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001456 // transform the dirty region into this screen's coordinate space
1457 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1458 if (!dirtyRegion.isEmpty()) {
1459 // redraw the whole screen
1460 doComposeSurfaces(hw, Region(hw->bounds()));
1461
1462 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001463 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001464 RenderEngine& engine(getRenderEngine());
1465 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1466
Mathias Agopianda27af92012-09-13 18:17:13 -07001467 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001468 }
1469 }
1470 }
1471
1472 postFramebuffer();
1473
1474 if (mDebugRegion > 1) {
1475 usleep(mDebugRegion * 1000);
1476 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001477
Dan Stoza9e56aa02015-11-02 13:00:03 -08001478 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001479 auto& displayDevice = mDisplays[displayId];
1480 if (!displayDevice->isDisplayOn()) {
1481 continue;
1482 }
1483
1484 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001485 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1486 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001487 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001488}
1489
Brian Andersond6927fb2016-07-23 23:37:30 -07001490void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001491{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001492 ATRACE_CALL();
1493 ALOGV("preComposition");
1494
Mathias Agopiancd60f992012-08-16 16:28:27 -07001495 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001496 mDrawingState.traverseInZOrder([&](Layer* layer) {
1497 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001498 needExtraInvalidate = true;
1499 }
Robert Carr2047fae2016-11-28 14:09:09 -08001500 });
1501
Mathias Agopiancd60f992012-08-16 16:28:27 -07001502 if (needExtraInvalidate) {
1503 signalLayerUpdate();
1504 }
1505}
1506
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001507void SurfaceFlinger::updateCompositorTiming(
1508 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1509 std::shared_ptr<FenceTime>& presentFenceTime) {
1510 // Update queue of past composite+present times and determine the
1511 // most recently known composite to present latency.
1512 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1513 nsecs_t compositeToPresentLatency = -1;
1514 while (!mCompositePresentTimes.empty()) {
1515 CompositePresentTime& cpt = mCompositePresentTimes.front();
1516 // Cached values should have been updated before calling this method,
1517 // which helps avoid duplicate syscalls.
1518 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1519 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1520 break;
1521 }
1522 compositeToPresentLatency = displayTime - cpt.composite;
1523 mCompositePresentTimes.pop();
1524 }
1525
1526 // Don't let mCompositePresentTimes grow unbounded, just in case.
1527 while (mCompositePresentTimes.size() > 16) {
1528 mCompositePresentTimes.pop();
1529 }
1530
Brian Andersond0010582017-03-07 13:20:31 -08001531 setCompositorTimingSnapped(
1532 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1533}
1534
1535void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1536 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001537 // Integer division and modulo round toward 0 not -inf, so we need to
1538 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001539 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001540 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1541 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1542
Brian Andersond0010582017-03-07 13:20:31 -08001543 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1544 if (idealLatency <= 0) {
1545 idealLatency = vsyncInterval;
1546 }
1547
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001548 // Snap the latency to a value that removes scheduling jitter from the
1549 // composition and present times, which often have >1ms of jitter.
1550 // Reducing jitter is important if an app attempts to extrapolate
1551 // something (such as user input) to an accurate diasplay time.
1552 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1553 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001554 nsecs_t bias = vsyncInterval / 2;
1555 int64_t extraVsyncs =
1556 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1557 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1558 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001559
Brian Andersond0010582017-03-07 13:20:31 -08001560 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001561 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1562 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001563 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001564}
1565
1566void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001567{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001568 ATRACE_CALL();
1569 ALOGV("postComposition");
1570
Brian Anderson3546a3f2016-07-14 11:51:14 -07001571 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001572 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001573 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001574 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001575 }
1576
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001577 // |mStateLock| not needed as we are on the main thread
1578 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001579
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001580 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001581 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1582 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1583 glCompositionDoneFenceTime =
1584 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1585 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1586 } else {
1587 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1588 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001589
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001590 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001591 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1592 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1593 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001594
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001595 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1596 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1597
1598 // We use the refreshStartTime which might be sampled a little later than
1599 // when we started doing work for this frame, but that should be okay
1600 // since updateCompositorTiming has snapping logic.
1601 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001602 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001603 CompositorTiming compositorTiming;
1604 {
1605 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1606 compositorTiming = mCompositorTiming;
1607 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001608
Robert Carr2047fae2016-11-28 14:09:09 -08001609 mDrawingState.traverseInZOrder([&](Layer* layer) {
1610 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001611 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001612 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001613 recordBufferingStats(layer->getName().string(),
1614 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001615 }
Robert Carr2047fae2016-11-28 14:09:09 -08001616 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001617
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001618 if (presentFenceTime->isValid()) {
1619 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001620 enableHardwareVsync();
1621 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001622 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001623 }
1624 }
1625
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001626 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001627 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001628 enableHardwareVsync();
1629 }
1630 }
1631
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001632 if (mAnimCompositionPending) {
1633 mAnimCompositionPending = false;
1634
Brian Anderson4e606e32017-03-16 15:34:57 -07001635 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001636 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001637 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001638 } else {
1639 // The HWC doesn't support present fences, so use the refresh
1640 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001641 nsecs_t presentTime =
1642 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001643 mAnimFrameTracker.setActualPresentTime(presentTime);
1644 }
1645 mAnimFrameTracker.advanceFrame();
1646 }
Dan Stozab90cf072015-03-05 11:05:59 -08001647
1648 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1649 return;
1650 }
1651
1652 nsecs_t currentTime = systemTime();
1653 if (mHasPoweredOff) {
1654 mHasPoweredOff = false;
1655 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001656 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001657 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001658 if (numPeriods < NUM_BUCKETS - 1) {
1659 mFrameBuckets[numPeriods] += elapsedTime;
1660 } else {
1661 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1662 }
1663 mTotalTime += elapsedTime;
1664 }
1665 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001666}
1667
1668void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001669 ATRACE_CALL();
1670 ALOGV("rebuildLayerStacks");
1671
Mathias Agopiancd60f992012-08-16 16:28:27 -07001672 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001673 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1674 ATRACE_CALL();
1675 mVisibleRegionsDirty = false;
1676 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001677
Jeff Sharkey76488112017-02-27 14:15:18 -07001678 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1679 Region opaqueRegion;
1680 Region dirtyRegion;
1681 Vector<sp<Layer>> layersSortedByZ;
1682 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1683 const Transform& tr(displayDevice->getTransform());
1684 const Rect bounds(displayDevice->getBounds());
1685 if (displayDevice->isDisplayOn()) {
1686 computeVisibleRegions(
1687 displayDevice->getLayerStack(), dirtyRegion,
1688 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001689
Jeff Sharkey76488112017-02-27 14:15:18 -07001690 mDrawingState.traverseInZOrder([&](Layer* layer) {
1691 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1692 Region drawRegion(tr.transform(
1693 layer->visibleNonTransparentRegion));
1694 drawRegion.andSelf(bounds);
1695 if (!drawRegion.isEmpty()) {
1696 layersSortedByZ.add(layer);
1697 } else {
1698 // Clear out the HWC layer if this layer was
1699 // previously visible, but no longer is
1700 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1701 nullptr);
1702 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001703 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001704 // WM changes displayDevice->layerStack upon sleep/awake.
1705 // Here we make sure we delete the HWC layers even if
1706 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001707 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1708 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001709 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001710 });
1711 }
1712 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1713 displayDevice->undefinedRegion.set(bounds);
1714 displayDevice->undefinedRegion.subtractSelf(
1715 tr.transform(opaqueRegion));
1716 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001717 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001718 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001719}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001720
Romain Guy0147a172017-06-01 13:53:56 -07001721mat4 SurfaceFlinger::computeSaturationMatrix() const {
1722 if (mSaturation == 1.0f) {
1723 return mat4();
1724 }
1725
1726 // Rec.709 luma coefficients
1727 float3 luminance{0.213f, 0.715f, 0.072f};
1728 luminance *= 1.0f - mSaturation;
1729 return mat4(
1730 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1731 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1732 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1733 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1734 );
1735}
1736
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001737// pickColorMode translates a given dataspace into the best available color mode.
1738// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001739android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001740 switch (dataSpace) {
1741 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1742 // system expects.
1743 case HAL_DATASPACE_UNKNOWN:
1744 case HAL_DATASPACE_SRGB:
1745 case HAL_DATASPACE_V0_SRGB:
1746 return HAL_COLOR_MODE_SRGB;
1747 break;
1748
1749 case HAL_DATASPACE_DISPLAY_P3:
1750 return HAL_COLOR_MODE_DISPLAY_P3;
1751 break;
1752
1753 default:
1754 // TODO (courtneygo): Do we want to assert an error here?
1755 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1756 dataSpace);
1757 return HAL_COLOR_MODE_SRGB;
1758 break;
1759 }
1760}
1761
Romain Guy0147a172017-06-01 13:53:56 -07001762android_dataspace SurfaceFlinger::bestTargetDataSpace(
1763 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001764 // Only support sRGB and Display-P3 right now.
1765 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1766 return HAL_DATASPACE_DISPLAY_P3;
1767 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001768 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1769 return HAL_DATASPACE_DISPLAY_P3;
1770 }
1771 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1772 return HAL_DATASPACE_DISPLAY_P3;
1773 }
1774
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001775 return HAL_DATASPACE_V0_SRGB;
1776}
1777
Mathias Agopiancd60f992012-08-16 16:28:27 -07001778void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001779 ATRACE_CALL();
1780 ALOGV("setUpHWComposer");
1781
Jesse Hall028dc8f2013-08-20 16:35:32 -07001782 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001783 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1784 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1785 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1786
1787 // If nothing has changed (!dirty), don't recompose.
1788 // If something changed, but we don't currently have any visible layers,
1789 // and didn't when we last did a composition, then skip it this time.
1790 // The second rule does two things:
1791 // - When all layers are removed from a display, we'll emit one black
1792 // frame, then nothing more until we get new layers.
1793 // - When a display is created with a private layer stack, we won't
1794 // emit any black frames until a layer is added to the layer stack.
1795 bool mustRecompose = dirty && !(empty && wasEmpty);
1796
1797 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1798 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1799 mustRecompose ? "doing" : "skipping",
1800 dirty ? "+" : "-",
1801 empty ? "+" : "-",
1802 wasEmpty ? "+" : "-");
1803
Dan Stoza71433162014-02-04 16:22:36 -08001804 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001805
1806 if (mustRecompose) {
1807 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1808 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001809 }
1810
Dan Stoza9e56aa02015-11-02 13:00:03 -08001811 // build the h/w work list
1812 if (CC_UNLIKELY(mGeometryInvalid)) {
1813 mGeometryInvalid = false;
1814 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1815 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1816 const auto hwcId = displayDevice->getHwcDisplayId();
1817 if (hwcId >= 0) {
1818 const Vector<sp<Layer>>& currentLayers(
1819 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001820 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001821 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001822 if (!layer->hasHwcLayer(hwcId)) {
1823 auto hwcLayer = mHwc->createLayer(hwcId);
1824 if (hwcLayer) {
1825 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1826 } else {
1827 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001828 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001829 }
1830 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001831
Robert Carrae060832016-11-28 10:51:00 -08001832 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001833 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001834 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001835 }
1836 }
1837 }
1838 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001839 }
Riley Andrews03414a12014-07-01 14:22:59 -07001840
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001841
Romain Guy0147a172017-06-01 13:53:56 -07001842 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001843
Dan Stoza9e56aa02015-11-02 13:00:03 -08001844 // Set the per-frame data
1845 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1846 auto& displayDevice = mDisplays[displayId];
1847 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001848
Dan Stoza9e56aa02015-11-02 13:00:03 -08001849 if (hwcId < 0) {
1850 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001851 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001852 if (colorMatrix != mPreviousColorMatrix) {
1853 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1854 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1855 "display %zd: %d", displayId, result);
1856 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001857 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1858 layer->setPerFrameData(displayDevice);
1859 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001860
1861 if (hasWideColorDisplay) {
1862 android_color_mode newColorMode;
1863 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1864
1865 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1866 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1867 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1868 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1869 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1870 }
1871 newColorMode = pickColorMode(newDataSpace);
1872
Romain Guyc53d3552017-07-20 18:49:46 -07001873 // We want the color mode of the boot animation to match that of the bootloader
1874 // To achieve this we suppress color mode changes until after the boot animation
1875 if (mBootFinished) {
1876 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001877 displayDevice->setCompositionDataSpace(newDataSpace);
Romain Guyc53d3552017-07-20 18:49:46 -07001878 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001879 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001880 }
1881
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001882 mPreviousColorMatrix = colorMatrix;
1883
Dan Stoza9e56aa02015-11-02 13:00:03 -08001884 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001885 auto& displayDevice = mDisplays[displayId];
1886 if (!displayDevice->isDisplayOn()) {
1887 continue;
1888 }
1889
1890 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1892 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001893 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001894}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001895
Mathias Agopiancd60f992012-08-16 16:28:27 -07001896void SurfaceFlinger::doComposition() {
1897 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001898 ALOGV("doComposition");
1899
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001900 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001901 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001902 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001903 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001904 // transform the dirty region into this screen's coordinate space
1905 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001906
1907 // repaint the framebuffer (if needed)
1908 doDisplayComposition(hw, dirtyRegion);
1909
Mathias Agopiancd60f992012-08-16 16:28:27 -07001910 hw->dirtyRegion.clear();
1911 hw->flip(hw->swapRegion);
1912 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001913 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001914 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001915 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001916}
1917
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001918void SurfaceFlinger::postFramebuffer()
1919{
Mathias Agopian841cde52012-03-01 15:44:37 -08001920 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001921 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001922
Mathias Agopiana44b0412011-10-16 18:46:35 -07001923 const nsecs_t now = systemTime();
1924 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001925
Dan Stoza9e56aa02015-11-02 13:00:03 -08001926 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1927 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001928 if (!displayDevice->isDisplayOn()) {
1929 continue;
1930 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001931 const auto hwcId = displayDevice->getHwcDisplayId();
1932 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001933 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001934 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001935 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001936 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001937 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1938 sp<Fence> releaseFence = Fence::NO_FENCE;
1939 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1940 releaseFence = displayDevice->getClientTargetAcquireFence();
1941 } else {
1942 auto hwcLayer = layer->getHwcLayer(hwcId);
1943 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001944 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001945 layer->onLayerDisplayed(releaseFence);
1946 }
1947 if (hwcId >= 0) {
1948 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001949 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001950 }
1951
Mathias Agopiana44b0412011-10-16 18:46:35 -07001952 mLastSwapBufferTime = systemTime() - now;
1953 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001954
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001955 // |mStateLock| not needed as we are on the main thread
1956 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001957 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1958 logFrameStats();
1959 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001960}
1961
Mathias Agopian87baae12012-07-31 12:38:26 -07001962void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001963{
Mathias Agopian841cde52012-03-01 15:44:37 -08001964 ATRACE_CALL();
1965
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001966 // here we keep a copy of the drawing state (that is the state that's
1967 // going to be overwritten by handleTransactionLocked()) outside of
1968 // mStateLock so that the side-effects of the State assignment
1969 // don't happen with mStateLock held (which can cause deadlocks).
1970 State drawingState(mDrawingState);
1971
Mathias Agopianca4d3602011-05-19 15:38:14 -07001972 Mutex::Autolock _l(mStateLock);
1973 const nsecs_t now = systemTime();
1974 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001975
Mathias Agopianca4d3602011-05-19 15:38:14 -07001976 // Here we're guaranteed that some transaction flags are set
1977 // so we can call handleTransactionLocked() unconditionally.
1978 // We call getTransactionFlags(), which will also clear the flags,
1979 // with mStateLock held to guarantee that mCurrentState won't change
1980 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001981
Mathias Agopiane57f2922012-08-09 16:29:12 -07001982 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001983 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001984
Mathias Agopianca4d3602011-05-19 15:38:14 -07001985 mLastTransactionTime = systemTime() - now;
1986 mDebugInTransaction = 0;
1987 invalidateHwcGeometry();
1988 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001989}
1990
Mathias Agopian87baae12012-07-31 12:38:26 -07001991void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001992{
Dan Stoza7dde5992015-05-22 09:51:44 -07001993 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001994 mCurrentState.traverseInZOrder([](Layer* layer) {
1995 layer->notifyAvailableFrames();
1996 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001997
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001998 /*
1999 * Traversal of the children
2000 * (perform the transaction for each of them if needed)
2001 */
2002
Mathias Agopian3559b072012-08-15 13:46:03 -07002003 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002004 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002005 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002006 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002007
2008 const uint32_t flags = layer->doTransaction(0);
2009 if (flags & Layer::eVisibleRegion)
2010 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002011 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002012 }
2013
2014 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002015 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002016 */
2017
Mathias Agopiane57f2922012-08-09 16:29:12 -07002018 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002019 // here we take advantage of Vector's copy-on-write semantics to
2020 // improve performance by skipping the transaction entirely when
2021 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002022 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2023 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002024 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002025 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002026 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002027 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002028
2029 // find the displays that were removed
2030 // (ie: in drawing state but not in current state)
2031 // also handle displays that changed
2032 // (ie: displays that are in both lists)
2033 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002034 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2035 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002036 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002037 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002038 // Call makeCurrent() on the primary display so we can
2039 // be sure that nothing associated with this display
2040 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002041 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002042 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002043 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002044 if (hw != NULL)
2045 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002046 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002047 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002048 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002049 } else {
2050 ALOGW("trying to remove the main display");
2051 }
2052 } else {
2053 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002054 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002055 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002056 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2057 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002058 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002059 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002060 // recreating the DisplayDevice, so we just remove it
2061 // from the drawing state, so that it get re-added
2062 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002063 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002064 if (hw != NULL)
2065 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002066 mDisplays.removeItem(display);
2067 mDrawingState.displays.removeItemsAt(i);
2068 dc--; i--;
2069 // at this point we must loop to the next item
2070 continue;
2071 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002072
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002073 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002074 if (disp != NULL) {
2075 if (state.layerStack != draw[i].layerStack) {
2076 disp->setLayerStack(state.layerStack);
2077 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002078 if ((state.orientation != draw[i].orientation)
2079 || (state.viewport != draw[i].viewport)
2080 || (state.frame != draw[i].frame))
2081 {
2082 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002083 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002084 }
Michael Lentine47e45402014-07-18 15:34:25 -07002085 if (state.width != draw[i].width || state.height != draw[i].height) {
2086 disp->setDisplaySize(state.width, state.height);
2087 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002088 }
2089 }
2090 }
2091
2092 // find displays that were added
2093 // (ie: in current state but not in drawing state)
2094 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002095 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002096 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002097
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002098 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002099 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002100 sp<IGraphicBufferProducer> bqProducer;
2101 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002102 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002103
Dan Stoza9e56aa02015-11-02 13:00:03 -08002104 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002105 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002106 // Virtual displays without a surface are dormant:
2107 // they have external state (layer stack, projection,
2108 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002109 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002110
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002111 // Allow VR composer to use virtual displays.
2112 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002113 int width = 0;
2114 int status = state.surface->query(
2115 NATIVE_WINDOW_WIDTH, &width);
2116 ALOGE_IF(status != NO_ERROR,
2117 "Unable to query width (%d)", status);
2118 int height = 0;
2119 status = state.surface->query(
2120 NATIVE_WINDOW_HEIGHT, &height);
2121 ALOGE_IF(status != NO_ERROR,
2122 "Unable to query height (%d)", status);
2123 int intFormat = 0;
2124 status = state.surface->query(
2125 NATIVE_WINDOW_FORMAT, &intFormat);
2126 ALOGE_IF(status != NO_ERROR,
2127 "Unable to query format (%d)", status);
2128 auto format = static_cast<android_pixel_format_t>(
2129 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002130
Dan Stoza8cf150a2016-08-02 10:27:31 -07002131 mHwc->allocateVirtualDisplay(width, height, &format,
2132 &hwcId);
2133 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002134
Dan Stoza5cf424b2016-05-20 14:02:39 -07002135 // TODO: Plumb requested format back up to consumer
2136
Dan Stoza9e56aa02015-11-02 13:00:03 -08002137 sp<VirtualDisplaySurface> vds =
2138 new VirtualDisplaySurface(*mHwc,
2139 hwcId, state.surface, bqProducer,
2140 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002141
2142 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002143 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002144 }
2145 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002146 ALOGE_IF(state.surface!=NULL,
2147 "adding a supported display, but rendering "
2148 "surface is provided (%p), ignoring it",
2149 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002150
2151 hwcId = state.type;
2152 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2153 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002154 }
2155
2156 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002157 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002158 sp<DisplayDevice> hw =
2159 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2160 dispSurface, producer,
2161 mRenderEngine->getEGLConfig(),
2162 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002163 hw->setLayerStack(state.layerStack);
2164 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002165 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002166 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002167 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002168 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002169 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002170 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002171 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002172 }
2173 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002174 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002175 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002176
Mathias Agopian84300952012-11-21 16:02:13 -08002177 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2178 // The transform hint might have changed for some layers
2179 // (either because a display has changed, or because a layer
2180 // as changed).
2181 //
2182 // Walk through all the layers in currentLayers,
2183 // and update their transform hint.
2184 //
2185 // If a layer is visible only on a single display, then that
2186 // display is used to calculate the hint, otherwise we use the
2187 // default display.
2188 //
2189 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2190 // the hint is set before we acquire a buffer from the surface texture.
2191 //
2192 // NOTE: layer transactions have taken place already, so we use their
2193 // drawing state. However, SurfaceFlinger's own transaction has not
2194 // happened yet, so we must use the current state layer list
2195 // (soon to become the drawing state list).
2196 //
2197 sp<const DisplayDevice> disp;
2198 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002199 bool first = true;
2200 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002201 // NOTE: we rely on the fact that layers are sorted by
2202 // layerStack first (so we don't have to traverse the list
2203 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002204 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002205 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002206 currentlayerStack = layerStack;
2207 // figure out if this layerstack is mirrored
2208 // (more than one display) if so, pick the default display,
2209 // if not, pick the only display it's on.
2210 disp.clear();
2211 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2212 sp<const DisplayDevice> hw(mDisplays[dpy]);
2213 if (hw->getLayerStack() == currentlayerStack) {
2214 if (disp == NULL) {
2215 disp = hw;
2216 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002217 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002218 break;
2219 }
2220 }
2221 }
2222 }
Chet Haase91d25932013-04-11 15:24:55 -07002223 if (disp == NULL) {
2224 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2225 // redraw after transform hint changes. See bug 8508397.
2226
2227 // could be null when this layer is using a layerStack
2228 // that is not visible on any display. Also can occur at
2229 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002230 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002231 }
Chet Haase91d25932013-04-11 15:24:55 -07002232 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002233
2234 first = false;
2235 });
Mathias Agopian84300952012-11-21 16:02:13 -08002236 }
2237
2238
Mathias Agopian3559b072012-08-15 13:46:03 -07002239 /*
2240 * Perform our own transaction if needed
2241 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002242
2243 if (mLayersAdded) {
2244 mLayersAdded = false;
2245 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002246 mVisibleRegionsDirty = true;
2247 }
2248
2249 // some layers might have been removed, so
2250 // we need to update the regions they're exposing.
2251 if (mLayersRemoved) {
2252 mLayersRemoved = false;
2253 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002254 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002255 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002256 // this layer is not visible anymore
2257 // TODO: we could traverse the tree from front to back and
2258 // compute the actual visible region
2259 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002260 Region visibleReg;
2261 visibleReg.set(layer->computeScreenBounds());
2262 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002263 }
Robert Carr2047fae2016-11-28 14:09:09 -08002264 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002265 }
2266
2267 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002268
2269 updateCursorAsync();
2270}
2271
2272void SurfaceFlinger::updateCursorAsync()
2273{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002274 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2275 auto& displayDevice = mDisplays[displayId];
2276 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002277 continue;
2278 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002279
2280 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2281 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002282 }
2283 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002284}
2285
2286void SurfaceFlinger::commitTransaction()
2287{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002288 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002289 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002290 for (const auto& l : mLayersPendingRemoval) {
2291 recordBufferingStats(l->getName().string(),
2292 l->getOccupancyHistory(true));
2293 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002294 }
2295 mLayersPendingRemoval.clear();
2296 }
2297
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002298 // If this transaction is part of a window animation then the next frame
2299 // we composite should be considered an animation as well.
2300 mAnimCompositionPending = mAnimTransactionPending;
2301
Mathias Agopian4fec8732012-06-29 14:12:52 -07002302 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002303 mDrawingState.traverseInZOrder([](Layer* layer) {
2304 layer->commitChildList();
2305 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002306 mTransactionPending = false;
2307 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002308 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309}
2310
Robert Carr2047fae2016-11-28 14:09:09 -08002311void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002312 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313{
Mathias Agopian841cde52012-03-01 15:44:37 -08002314 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002315 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002316
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002317 Region aboveOpaqueLayers;
2318 Region aboveCoveredLayers;
2319 Region dirty;
2320
Mathias Agopian87baae12012-07-31 12:38:26 -07002321 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002322
Robert Carr2047fae2016-11-28 14:09:09 -08002323 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002324 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002325 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002326
Jesse Hall01e29052013-02-19 16:13:35 -08002327 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002328 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002329 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002330
Mathias Agopianab028732010-03-16 16:41:46 -07002331 /*
2332 * opaqueRegion: area of a surface that is fully opaque.
2333 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002334 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002335
2336 /*
2337 * visibleRegion: area of a surface that is visible on screen
2338 * and not fully transparent. This is essentially the layer's
2339 * footprint minus the opaque regions above it.
2340 * Areas covered by a translucent surface are considered visible.
2341 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002343
2344 /*
2345 * coveredRegion: area of a surface that is covered by all
2346 * visible regions above it (which includes the translucent areas).
2347 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002348 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002349
Jesse Halla8026d22012-09-25 13:25:04 -07002350 /*
2351 * transparentRegion: area of a surface that is hinted to be completely
2352 * transparent. This is only used to tell when the layer has no visible
2353 * non-transparent regions and can be removed from the layer list. It
2354 * does not affect the visibleRegion of this layer or any layers
2355 * beneath it. The hint may not be correct if apps don't respect the
2356 * SurfaceView restrictions (which, sadly, some don't).
2357 */
2358 Region transparentRegion;
2359
Mathias Agopianab028732010-03-16 16:41:46 -07002360
2361 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002362 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002363 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002364 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002365 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002366 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002367 if (!visibleRegion.isEmpty()) {
2368 // Remove the transparent area from the visible region
2369 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002370 if (tr.preserveRects()) {
2371 // transform the transparent region
2372 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002373 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002374 // transformation too complex, can't do the
2375 // transparent region optimization.
2376 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002377 }
Mathias Agopianab028732010-03-16 16:41:46 -07002378 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002379
Mathias Agopianab028732010-03-16 16:41:46 -07002380 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002381 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002382 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002383 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2384 // the opaque region is the layer's footprint
2385 opaqueRegion = visibleRegion;
2386 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002387 }
2388 }
2389
Mathias Agopianab028732010-03-16 16:41:46 -07002390 // Clip the covered region to the visible region
2391 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2392
2393 // Update aboveCoveredLayers for next (lower) layer
2394 aboveCoveredLayers.orSelf(visibleRegion);
2395
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002396 // subtract the opaque region covered by the layers above us
2397 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002398
2399 // compute this layer's dirty region
2400 if (layer->contentDirty) {
2401 // we need to invalidate the whole region
2402 dirty = visibleRegion;
2403 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002404 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002405 layer->contentDirty = false;
2406 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002407 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002408 * the exposed region consists of two components:
2409 * 1) what's VISIBLE now and was COVERED before
2410 * 2) what's EXPOSED now less what was EXPOSED before
2411 *
2412 * note that (1) is conservative, we start with the whole
2413 * visible region but only keep what used to be covered by
2414 * something -- which mean it may have been exposed.
2415 *
2416 * (2) handles areas that were not covered by anything but got
2417 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002418 */
Mathias Agopianab028732010-03-16 16:41:46 -07002419 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002420 const Region oldVisibleRegion = layer->visibleRegion;
2421 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002422 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2423 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002424 }
2425 dirty.subtractSelf(aboveOpaqueLayers);
2426
2427 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002428 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002429
Mathias Agopianab028732010-03-16 16:41:46 -07002430 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002431 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002432
Jesse Halla8026d22012-09-25 13:25:04 -07002433 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002434 layer->setVisibleRegion(visibleRegion);
2435 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002436 layer->setVisibleNonTransparentRegion(
2437 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002438 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439
Mathias Agopian87baae12012-07-31 12:38:26 -07002440 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002441}
2442
Mathias Agopian87baae12012-07-31 12:38:26 -07002443void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2444 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002445 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002446 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2447 if (hw->getLayerStack() == layerStack) {
2448 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002449 }
2450 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002451}
2452
Dan Stoza6b9454d2014-11-07 16:00:59 -08002453bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002455 ALOGV("handlePageFlip");
2456
Brian Andersond6927fb2016-07-23 23:37:30 -07002457 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002458
Mathias Agopian4fec8732012-06-29 14:12:52 -07002459 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002460 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002461 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002462
2463 // Store the set of layers that need updates. This set must not change as
2464 // buffers are being latched, as this could result in a deadlock.
2465 // Example: Two producers share the same command stream and:
2466 // 1.) Layer 0 is latched
2467 // 2.) Layer 0 gets a new frame
2468 // 2.) Layer 1 gets a new frame
2469 // 3.) Layer 1 is latched.
2470 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2471 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002472 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002473 if (layer->hasQueuedFrame()) {
2474 frameQueued = true;
2475 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002476 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002477 } else {
2478 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002479 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002480 } else {
2481 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002482 }
Robert Carr2047fae2016-11-28 14:09:09 -08002483 });
2484
Dan Stoza9e56aa02015-11-02 13:00:03 -08002485 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002486 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002487 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002488 invalidateLayerStack(layer->getLayerStack(), dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002489 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002490 newDataLatched = true;
2491 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002492 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002493
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002494 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002495
2496 // If we will need to wake up at some time in the future to deal with a
2497 // queued frame that shouldn't be displayed during this vsync period, wake
2498 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002499 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002500 signalLayerUpdate();
2501 }
2502
2503 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002504 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002505}
2506
Mathias Agopianad456f92011-01-13 17:53:01 -08002507void SurfaceFlinger::invalidateHwcGeometry()
2508{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002509 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002510}
2511
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002512
Fabien Sanglard830b8472016-11-30 16:35:58 -08002513void SurfaceFlinger::doDisplayComposition(
2514 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002515 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516{
Dan Stoza71433162014-02-04 16:22:36 -08002517 // We only need to actually compose the display if:
2518 // 1) It is being handled by hardware composer, which may need this to
2519 // keep its virtual display state machine in sync, or
2520 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002521 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002522 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002523 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002524 return;
2525 }
2526
Dan Stoza9e56aa02015-11-02 13:00:03 -08002527 ALOGV("doDisplayComposition");
2528
Mathias Agopian87baae12012-07-31 12:38:26 -07002529 Region dirtyRegion(inDirtyRegion);
2530
Mathias Agopianb8a55602009-06-26 19:06:36 -07002531 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002532 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002533
Fabien Sanglard830b8472016-11-30 16:35:58 -08002534 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002535 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002536 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2537 // takes a rectangle, we must make sure to update that whole
2538 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002539 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002540 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002541 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002542 // We need to redraw the rectangle that will be updated
2543 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002544 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002545 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002546 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002547 } else {
2548 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002549 dirtyRegion.set(displayDevice->bounds());
2550 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551 }
2552 }
2553
Fabien Sanglard830b8472016-11-30 16:35:58 -08002554 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002555
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002556 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002557 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002558
2559 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002560 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561}
2562
Dan Stoza9e56aa02015-11-02 13:00:03 -08002563bool SurfaceFlinger::doComposeSurfaces(
2564 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002565{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002566 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002567
Dan Stoza9e56aa02015-11-02 13:00:03 -08002568 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002569
2570 mat4 oldColorMatrix;
2571 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2572 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2573 if (applyColorMatrix) {
2574 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2575 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2576 }
2577
Dan Stoza9e56aa02015-11-02 13:00:03 -08002578 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2579 if (hasClientComposition) {
2580 ALOGV("hasClientComposition");
2581
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002582#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002583 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002584 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002585#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002586 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002587 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002588 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002589 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002590
2591 // |mStateLock| not needed as we are on the main thread
2592 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002593 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2594 }
2595 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002596 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002597
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002598 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002599 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2600 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002601 // when using overlays, we assume a fully transparent framebuffer
2602 // NOTE: we could reduce how much we need to clear, for instance
2603 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002604 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002605 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002606 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002607 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002608 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002609 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002610
2611 // we remove the scissor part
2612 // we're left with the letterbox region
2613 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002614 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002615
2616 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002617 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002618
2619 // but limit it to the dirty region
2620 region.andSelf(dirty);
2621
Mathias Agopianb9494d52012-04-18 02:28:45 -07002622 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002623 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002624 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002625 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002626 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002627 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002628
Dan Stoza9e56aa02015-11-02 13:00:03 -08002629 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002630 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002631 // scissor on the main display. It should never be needed
2632 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002633 const Rect& bounds(displayDevice->getBounds());
2634 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002635 if (scissor != bounds) {
2636 // scissor doesn't match the screen's dimensions, so we
2637 // need to clear everything outside of it and enable
2638 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002639
Mathias Agopianf45c5102012-10-24 16:29:17 -07002640 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002641 const uint32_t height = displayDevice->getHeight();
2642 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002643 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002644 }
2645 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002646 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002647
Mathias Agopian85d751c2012-08-29 16:59:24 -07002648 /*
2649 * and then, render the layers targeted at the framebuffer
2650 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002651
Dan Stoza9e56aa02015-11-02 13:00:03 -08002652 ALOGV("Rendering client layers");
2653 const Transform& displayTransform = displayDevice->getTransform();
2654 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002655 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002656 bool firstLayer = true;
2657 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2658 const Region clip(dirty.intersect(
2659 displayTransform.transform(layer->visibleRegion)));
2660 ALOGV("Layer: %s", layer->getName().string());
2661 ALOGV(" Composition type: %s",
2662 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002663 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002664 switch (layer->getCompositionType(hwcId)) {
2665 case HWC2::Composition::Cursor:
2666 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002667 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002668 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002669 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002670 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2671 layer->isOpaque(state) && (state.alpha == 1.0f)
2672 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002673 // never clear the very first layer since we're
2674 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002675 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002676 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002677 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002678 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002679 case HWC2::Composition::Client: {
2680 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002681 break;
2682 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002683 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002684 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002685 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002686 } else {
2687 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002688 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002689 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002690 }
2691 } else {
2692 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002694 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002695 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002696 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002697 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002698 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002699 }
2700 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002701
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002702 if (applyColorMatrix) {
2703 getRenderEngine().setupColorTransform(oldColorMatrix);
2704 }
2705
Mathias Agopianf45c5102012-10-24 16:29:17 -07002706 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002707 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002708 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709}
2710
Fabien Sanglard830b8472016-11-30 16:35:58 -08002711void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2712 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002713 RenderEngine& engine(getRenderEngine());
2714 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715}
2716
Dan Stoza7d89d062015-04-30 13:29:25 -07002717status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002718 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002719 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002720 const sp<Layer>& lbc,
2721 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002722{
Dan Stoza7d89d062015-04-30 13:29:25 -07002723 // add this layer to the current state list
2724 {
2725 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002726 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002727 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2728 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002729 return NO_MEMORY;
2730 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002731 if (parent == nullptr) {
2732 mCurrentState.layersSortedByZ.add(lbc);
2733 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002734 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2735 ALOGE("addClientLayer called with a removed parent");
2736 return NAME_NOT_FOUND;
2737 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002738 parent->addChild(lbc);
2739 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002740
Dan Stoza7d89d062015-04-30 13:29:25 -07002741 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002742 mLayersAdded = true;
2743 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002744 }
2745
Mathias Agopian96f08192010-06-02 23:28:45 -07002746 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002747 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002748
Dan Stoza7d89d062015-04-30 13:29:25 -07002749 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002750}
2751
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002752status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002753 Mutex::Autolock _l(mStateLock);
2754
Robert Carr1f0a16a2016-10-24 16:27:39 -07002755 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002756 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002757 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002758 if (topLevelOnly) {
2759 return NO_ERROR;
2760 }
2761
Chia-I Wu98f1c102017-05-30 14:54:08 -07002762 sp<Layer> ancestor = p;
2763 while (ancestor->getParent() != nullptr) {
2764 ancestor = ancestor->getParent();
2765 }
2766 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2767 ALOGE("removeLayer called with a layer whose parent has been removed");
2768 return NAME_NOT_FOUND;
2769 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002770
2771 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002772 } else {
2773 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002774 }
2775
Robert Carr136e2f62017-02-08 17:54:29 -08002776 // As a matter of normal operation, the LayerCleaner will produce a second
2777 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2778 // so we will succeed in promoting it, but it's already been removed
2779 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2780 // otherwise something has gone wrong and we are leaking the layer.
2781 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002782 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2783 layer->getName().string(),
2784 (p != nullptr) ? p->getName().string() : "no-parent");
2785 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002786 } else if (index < 0) {
2787 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002788 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002789
2790 mLayersPendingRemoval.add(layer);
2791 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002792 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002793 setTransactionFlags(eTransactionNeeded);
2794 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795}
2796
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002797uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002798 return android_atomic_release_load(&mTransactionFlags);
2799}
2800
Mathias Agopian3f844832013-08-07 21:24:32 -07002801uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2803}
2804
Mathias Agopian3f844832013-08-07 21:24:32 -07002805uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2807 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002808 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809 }
2810 return old;
2811}
2812
Mathias Agopian8b33f032012-07-24 20:43:54 -07002813void SurfaceFlinger::setTransactionState(
2814 const Vector<ComposerState>& state,
2815 const Vector<DisplayState>& displays,
2816 uint32_t flags)
2817{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002818 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002819 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002820 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002821
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002822 if (flags & eAnimation) {
2823 // For window updates that are part of an animation we must wait for
2824 // previous animation "frames" to be handled.
2825 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002826 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002827 if (CC_UNLIKELY(err != NO_ERROR)) {
2828 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002829 // caller after a few seconds.
2830 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2831 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002832 mAnimTransactionPending = false;
2833 break;
2834 }
2835 }
2836 }
2837
Mathias Agopiane57f2922012-08-09 16:29:12 -07002838 size_t count = displays.size();
2839 for (size_t i=0 ; i<count ; i++) {
2840 const DisplayState& s(displays[i]);
2841 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002842 }
2843
Mathias Agopiane57f2922012-08-09 16:29:12 -07002844 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002845 for (size_t i=0 ; i<count ; i++) {
2846 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002847 // Here we need to check that the interface we're given is indeed
2848 // one of our own. A malicious client could give us a NULL
2849 // IInterface, or one of its own or even one of our own but a
2850 // different type. All these situations would cause us to crash.
2851 //
2852 // NOTE: it would be better to use RTTI as we could directly check
2853 // that we have a Client*. however, RTTI is disabled in Android.
2854 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002855 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002856 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002857 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002858 sp<Client> client( static_cast<Client *>(s.client.get()) );
2859 transactionFlags |= setClientStateLocked(client, s.state);
2860 }
2861 }
2862 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002863 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002864
Robert Carr2a7dbb42016-05-24 11:41:28 -07002865 // If a synchronous transaction is explicitly requested without any changes,
2866 // force a transaction anyway. This can be used as a flush mechanism for
2867 // previous async transactions.
2868 if (transactionFlags == 0 && (flags & eSynchronous)) {
2869 transactionFlags = eTransactionNeeded;
2870 }
2871
Mathias Agopian386aa982011-11-07 21:58:03 -08002872 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002873 if (mInterceptor.isEnabled()) {
2874 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2875 }
Irvel468051e2016-06-13 16:44:44 -07002876
Mathias Agopian386aa982011-11-07 21:58:03 -08002877 // this triggers the transaction
2878 setTransactionFlags(transactionFlags);
2879
2880 // if this is a synchronous transaction, wait for it to take effect
2881 // before returning.
2882 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002883 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002884 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002885 if (flags & eAnimation) {
2886 mAnimTransactionPending = true;
2887 }
2888 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002889 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2890 if (CC_UNLIKELY(err != NO_ERROR)) {
2891 // just in case something goes wrong in SF, return to the
2892 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002893 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2894 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002895 break;
2896 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002897 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898 }
2899}
2900
Mathias Agopiane57f2922012-08-09 16:29:12 -07002901uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2902{
Jesse Hall9a143922012-10-04 16:29:19 -07002903 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2904 if (dpyIdx < 0)
2905 return 0;
2906
Mathias Agopiane57f2922012-08-09 16:29:12 -07002907 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002908 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002909 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002910 const uint32_t what = s.what;
2911 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002912 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002913 disp.surface = s.surface;
2914 flags |= eDisplayTransactionNeeded;
2915 }
2916 }
2917 if (what & DisplayState::eLayerStackChanged) {
2918 if (disp.layerStack != s.layerStack) {
2919 disp.layerStack = s.layerStack;
2920 flags |= eDisplayTransactionNeeded;
2921 }
2922 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002923 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002924 if (disp.orientation != s.orientation) {
2925 disp.orientation = s.orientation;
2926 flags |= eDisplayTransactionNeeded;
2927 }
2928 if (disp.frame != s.frame) {
2929 disp.frame = s.frame;
2930 flags |= eDisplayTransactionNeeded;
2931 }
2932 if (disp.viewport != s.viewport) {
2933 disp.viewport = s.viewport;
2934 flags |= eDisplayTransactionNeeded;
2935 }
2936 }
Michael Lentine47e45402014-07-18 15:34:25 -07002937 if (what & DisplayState::eDisplaySizeChanged) {
2938 if (disp.width != s.width) {
2939 disp.width = s.width;
2940 flags |= eDisplayTransactionNeeded;
2941 }
2942 if (disp.height != s.height) {
2943 disp.height = s.height;
2944 flags |= eDisplayTransactionNeeded;
2945 }
2946 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002947 }
2948 return flags;
2949}
2950
2951uint32_t SurfaceFlinger::setClientStateLocked(
2952 const sp<Client>& client,
2953 const layer_state_t& s)
2954{
2955 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002956 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002957 if (layer != 0) {
2958 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002959 bool geometryAppliesWithResize =
2960 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002961 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002962 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002963 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002964 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002965 }
2966 if (what & layer_state_t::eLayerChanged) {
2967 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002968 const auto& p = layer->getParent();
2969 if (p == nullptr) {
2970 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2971 if (layer->setLayer(s.z) && idx >= 0) {
2972 mCurrentState.layersSortedByZ.removeAt(idx);
2973 mCurrentState.layersSortedByZ.add(layer);
2974 // we need traversal (state changed)
2975 // AND transaction (list changed)
2976 flags |= eTransactionNeeded|eTraversalNeeded;
2977 }
2978 } else {
2979 if (p->setChildLayer(layer, s.z)) {
2980 flags |= eTransactionNeeded|eTraversalNeeded;
2981 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002982 }
2983 }
Robert Carrdb66e622017-04-10 16:55:57 -07002984 if (what & layer_state_t::eRelativeLayerChanged) {
2985 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2986 flags |= eTransactionNeeded|eTraversalNeeded;
2987 }
2988 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002989 if (what & layer_state_t::eSizeChanged) {
2990 if (layer->setSize(s.w, s.h)) {
2991 flags |= eTraversalNeeded;
2992 }
2993 }
2994 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002995 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002996 flags |= eTraversalNeeded;
2997 }
2998 if (what & layer_state_t::eMatrixChanged) {
2999 if (layer->setMatrix(s.matrix))
3000 flags |= eTraversalNeeded;
3001 }
3002 if (what & layer_state_t::eTransparentRegionChanged) {
3003 if (layer->setTransparentRegionHint(s.transparentRegion))
3004 flags |= eTraversalNeeded;
3005 }
Dan Stoza23116082015-06-18 14:58:39 -07003006 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003007 if (layer->setFlags(s.flags, s.mask))
3008 flags |= eTraversalNeeded;
3009 }
3010 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003011 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003012 flags |= eTraversalNeeded;
3013 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003014 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003015 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003016 flags |= eTraversalNeeded;
3017 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003018 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003019 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003020 // We only allow setting layer stacks for top level layers,
3021 // everything else inherits layer stack from its parent.
3022 if (layer->hasParent()) {
3023 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3024 layer->getName().string());
3025 } else if (idx < 0) {
3026 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3027 "that also does not appear in the top level layer list. Something"
3028 " has gone wrong.", layer->getName().string());
3029 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003030 mCurrentState.layersSortedByZ.removeAt(idx);
3031 mCurrentState.layersSortedByZ.add(layer);
3032 // we need traversal (state changed)
3033 // AND transaction (list changed)
3034 flags |= eTransactionNeeded|eTraversalNeeded;
3035 }
3036 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003037 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003038 if (s.barrierHandle != nullptr) {
3039 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3040 } else if (s.barrierGbp != nullptr) {
3041 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3042 if (authenticateSurfaceTextureLocked(gbp)) {
3043 const auto& otherLayer =
3044 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3045 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3046 } else {
3047 ALOGE("Attempt to defer transaction to to an"
3048 " unrecognized GraphicBufferProducer");
3049 }
3050 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003051 // We don't trigger a traversal here because if no other state is
3052 // changed, we don't want this to cause any more work
3053 }
Robert Carr1db73f62016-12-21 12:58:51 -08003054 if (what & layer_state_t::eReparentChildren) {
3055 if (layer->reparentChildren(s.reparentHandle)) {
3056 flags |= eTransactionNeeded|eTraversalNeeded;
3057 }
3058 }
Robert Carr9524cb32017-02-13 11:32:32 -08003059 if (what & layer_state_t::eDetachChildren) {
3060 layer->detachChildren();
3061 }
Robert Carrc3574f72016-03-24 12:19:32 -07003062 if (what & layer_state_t::eOverrideScalingModeChanged) {
3063 layer->setOverrideScalingMode(s.overrideScalingMode);
3064 // We don't trigger a traversal here because if no other state is
3065 // changed, we don't want this to cause any more work
3066 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003067 }
3068 return flags;
3069}
3070
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003071status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003072 const String8& name,
3073 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003074 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003075 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3076 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003077{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003078 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003079 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003080 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003081 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003082 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003083
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003084 status_t result = NO_ERROR;
3085
3086 sp<Layer> layer;
3087
Cody Northropbc755282017-03-31 12:00:08 -06003088 String8 uniqueName = getUniqueLayerName(name);
3089
Mathias Agopian3165cc22012-08-08 19:42:09 -07003090 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3091 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003092 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003093 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003094 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003095 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003096 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003097 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003098 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003099 handle, gbp, &layer);
3100 break;
3101 default:
3102 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003103 break;
3104 }
3105
Dan Stoza7d89d062015-04-30 13:29:25 -07003106 if (result != NO_ERROR) {
3107 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003108 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003109
Albert Chaulk479c60c2017-01-27 14:21:34 -05003110 layer->setInfo(windowType, ownerUid);
3111
Robert Carr1f0a16a2016-10-24 16:27:39 -07003112 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003113 if (result != NO_ERROR) {
3114 return result;
3115 }
Irvelffc9efc2016-07-27 15:16:37 -07003116 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003117
3118 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003119 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120}
3121
Cody Northropbc755282017-03-31 12:00:08 -06003122String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3123{
3124 bool matchFound = true;
3125 uint32_t dupeCounter = 0;
3126
3127 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3128 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3129
3130 // Loop over layers until we're sure there is no matching name
3131 while (matchFound) {
3132 matchFound = false;
3133 mDrawingState.traverseInZOrder([&](Layer* layer) {
3134 if (layer->getName() == uniqueName) {
3135 matchFound = true;
3136 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3137 }
3138 });
3139 }
3140
3141 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3142
3143 return uniqueName;
3144}
3145
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003146status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3147 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3148 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003149{
3150 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003151 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152 case PIXEL_FORMAT_TRANSPARENT:
3153 case PIXEL_FORMAT_TRANSLUCENT:
3154 format = PIXEL_FORMAT_RGBA_8888;
3155 break;
3156 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003157 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158 break;
3159 }
3160
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003161 *outLayer = new Layer(this, client, name, w, h, flags);
3162 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3163 if (err == NO_ERROR) {
3164 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003165 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003167
3168 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3169 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170}
3171
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003172status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3173 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3174 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003176 *outLayer = new LayerDim(this, client, name, w, h, flags);
3177 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003178 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003179 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003180}
3181
Mathias Agopianac9fa422013-02-11 16:40:36 -08003182status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003183{
Robert Carr9524cb32017-02-13 11:32:32 -08003184 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003185 status_t err = NO_ERROR;
3186 sp<Layer> l(client->getLayerUser(handle));
3187 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003188 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003189 err = removeLayer(l);
3190 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3191 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003192 }
3193 return err;
3194}
3195
Mathias Agopian13127d82013-03-05 17:47:11 -08003196status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003197{
Mathias Agopian67106042013-03-14 19:18:13 -07003198 // called by ~LayerCleaner() when all references to the IBinder (handle)
3199 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003200 sp<Layer> l = layer.promote();
3201 if (l == nullptr) {
3202 // The layer has already been removed, carry on
3203 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003204 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003205 // If we have a parent, then we can continue to live as long as it does.
3206 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207}
3208
Mathias Agopianb60314a2012-04-10 22:09:54 -07003209// ---------------------------------------------------------------------------
3210
Andy McFadden13a082e2012-08-24 10:16:42 -07003211void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003212 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003213 Vector<ComposerState> state;
3214 Vector<DisplayState> displays;
3215 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003216 d.what = DisplayState::eDisplayProjectionChanged |
3217 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003218 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003219 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003220 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003221 d.frame.makeInvalid();
3222 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003223 d.width = 0;
3224 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003225 displays.add(d);
3226 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003227 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003228
Dan Stoza9e56aa02015-11-02 13:00:03 -08003229 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3230 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003231 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003232
Brian Andersond0010582017-03-07 13:20:31 -08003233 // Use phase of 0 since phase is not known.
3234 // Use latency of 0, which will snap to the ideal latency.
3235 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003236}
3237
3238void SurfaceFlinger::initializeDisplays() {
3239 class MessageScreenInitialized : public MessageBase {
3240 SurfaceFlinger* flinger;
3241 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003242 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003243 virtual bool handler() {
3244 flinger->onInitializeDisplays();
3245 return true;
3246 }
3247 };
3248 sp<MessageBase> msg = new MessageScreenInitialized(this);
3249 postMessageAsync(msg); // we may be called from main thread, use async message
3250}
3251
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003252void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3253 int mode) {
3254 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3255 this);
3256 int32_t type = hw->getDisplayType();
3257 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003258
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003259 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003260 return;
3261 }
3262
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003263 hw->setPowerMode(mode);
3264 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3265 ALOGW("Trying to set power mode for virtual display");
3266 return;
3267 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003268
Irvelffc9efc2016-07-27 15:16:37 -07003269 if (mInterceptor.isEnabled()) {
3270 Mutex::Autolock _l(mStateLock);
3271 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3272 if (idx < 0) {
3273 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3274 return;
3275 }
3276 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3277 }
3278
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003279 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003280 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003281 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003282 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3283 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003284 // FIXME: eventthread only knows about the main display right now
3285 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003286 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003287 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003288
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003289 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003290 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003291 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003292
3293 struct sched_param param = {0};
3294 param.sched_priority = 1;
3295 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3296 ALOGW("Couldn't set SCHED_FIFO on display on");
3297 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003298 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003299 // Turn off the display
3300 struct sched_param param = {0};
3301 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3302 ALOGW("Couldn't set SCHED_OTHER on display off");
3303 }
3304
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003305 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003306 disableHardwareVsync(true); // also cancels any in-progress resync
3307
Mathias Agopiancde87a32012-09-13 14:09:01 -07003308 // FIXME: eventthread only knows about the main display right now
3309 mEventThread->onScreenReleased();
3310 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003311
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003312 getHwComposer().setPowerMode(type, mode);
3313 mVisibleRegionsDirty = true;
3314 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003315 } else if (mode == HWC_POWER_MODE_DOZE ||
3316 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003317 // Update display while dozing
3318 getHwComposer().setPowerMode(type, mode);
3319 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3320 // FIXME: eventthread only knows about the main display right now
3321 mEventThread->onScreenAcquired();
3322 resyncToHardwareVsync(true);
3323 }
3324 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3325 // Leave display going to doze
3326 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3327 disableHardwareVsync(true); // also cancels any in-progress resync
3328 // FIXME: eventthread only knows about the main display right now
3329 mEventThread->onScreenReleased();
3330 }
3331 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003332 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003333 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003334 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003335 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003336}
3337
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003338void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3339 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003340 SurfaceFlinger& mFlinger;
3341 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003342 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003343 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003344 MessageSetPowerMode(SurfaceFlinger& flinger,
3345 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3346 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003347 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003348 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003349 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003350 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003351 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003352 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003353 ALOGW("Attempt to set power mode = %d for virtual display",
3354 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003355 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003356 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003357 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003358 return true;
3359 }
3360 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003361 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003362 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003363}
3364
3365// ---------------------------------------------------------------------------
3366
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003367status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3368{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003369 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003370
Mathias Agopianbd115332013-04-18 16:41:04 -07003371 IPCThreadState* ipc = IPCThreadState::self();
3372 const int pid = ipc->getCallingPid();
3373 const int uid = ipc->getCallingUid();
3374 if ((uid != AID_SHELL) &&
3375 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003376 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003377 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003378 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003379 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003380 // (this would indicate SF is stuck, but we want to be able to
3381 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003382 status_t err = mStateLock.timedLock(s2ns(1));
3383 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003384 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003385 result.appendFormat(
3386 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3387 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003388 }
3389
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003390 bool dumpAll = true;
3391 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003392 size_t numArgs = args.size();
3393 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003394 if ((index < numArgs) &&
3395 (args[index] == String16("--list"))) {
3396 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003397 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003398 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003399 }
3400
3401 if ((index < numArgs) &&
3402 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003403 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003404 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003405 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003406 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003407
3408 if ((index < numArgs) &&
3409 (args[index] == String16("--latency-clear"))) {
3410 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003411 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003412 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003413 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003414
3415 if ((index < numArgs) &&
3416 (args[index] == String16("--dispsync"))) {
3417 index++;
3418 mPrimaryDispSync.dump(result);
3419 dumpAll = false;
3420 }
Dan Stozab90cf072015-03-05 11:05:59 -08003421
3422 if ((index < numArgs) &&
3423 (args[index] == String16("--static-screen"))) {
3424 index++;
3425 dumpStaticScreenStats(result);
3426 dumpAll = false;
3427 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003428
3429 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003430 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003431 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003432 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003433 dumpAll = false;
3434 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003435
3436 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3437 index++;
3438 dumpWideColorInfo(result);
3439 dumpAll = false;
3440 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003441 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003442
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003443 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003444 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003445 }
3446
Mathias Agopian9795c422009-08-26 16:36:26 -07003447 if (locked) {
3448 mStateLock.unlock();
3449 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003450 }
3451 write(fd, result.string(), result.size());
3452 return NO_ERROR;
3453}
3454
Dan Stozac7014012014-02-14 15:03:43 -08003455void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3456 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003457{
Robert Carr2047fae2016-11-28 14:09:09 -08003458 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003459 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003460 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003461}
3462
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003463void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003464 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003465{
3466 String8 name;
3467 if (index < args.size()) {
3468 name = String8(args[index]);
3469 index++;
3470 }
3471
Dan Stoza9e56aa02015-11-02 13:00:03 -08003472 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3473 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003474 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003475
3476 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003477 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003478 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003479 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003480 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003481 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003482 }
Robert Carr2047fae2016-11-28 14:09:09 -08003483 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003484 }
3485}
3486
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003487void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003488 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003489{
3490 String8 name;
3491 if (index < args.size()) {
3492 name = String8(args[index]);
3493 index++;
3494 }
3495
Robert Carr2047fae2016-11-28 14:09:09 -08003496 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003497 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003498 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003499 }
Robert Carr2047fae2016-11-28 14:09:09 -08003500 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003501
Svetoslavd85084b2014-03-20 10:28:31 -07003502 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003503}
3504
Jamie Gennis6547ff42013-07-16 20:12:42 -07003505// This should only be called from the main thread. Otherwise it would need
3506// the lock and should use mCurrentState rather than mDrawingState.
3507void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003508 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003509 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003510 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003511
3512 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3513}
3514
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003515void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003516{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003517 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003518 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3519
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003520 if (isLayerTripleBufferingDisabled())
3521 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003522
3523 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003524 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003525 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003526 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003527 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3528 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003529 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003530}
3531
Dan Stozab90cf072015-03-05 11:05:59 -08003532void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3533{
3534 result.appendFormat("Static screen stats:\n");
3535 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3536 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3537 float percent = 100.0f *
3538 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3539 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3540 b + 1, bucketTimeSec, percent);
3541 }
3542 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3543 float percent = 100.0f *
3544 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3545 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3546 NUM_BUCKETS - 1, bucketTimeSec, percent);
3547}
3548
Dan Stozae77c7662016-05-13 11:37:28 -07003549void SurfaceFlinger::recordBufferingStats(const char* layerName,
3550 std::vector<OccupancyTracker::Segment>&& history) {
3551 Mutex::Autolock lock(mBufferingStatsMutex);
3552 auto& stats = mBufferingStats[layerName];
3553 for (const auto& segment : history) {
3554 if (!segment.usedThirdBuffer) {
3555 stats.twoBufferTime += segment.totalTime;
3556 }
3557 if (segment.occupancyAverage < 1.0f) {
3558 stats.doubleBufferedTime += segment.totalTime;
3559 } else if (segment.occupancyAverage < 2.0f) {
3560 stats.tripleBufferedTime += segment.totalTime;
3561 }
3562 ++stats.numSegments;
3563 stats.totalTime += segment.totalTime;
3564 }
3565}
3566
Brian Andersond6927fb2016-07-23 23:37:30 -07003567void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3568 result.appendFormat("Layer frame timestamps:\n");
3569
3570 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3571 const size_t count = currentLayers.size();
3572 for (size_t i=0 ; i<count ; i++) {
3573 currentLayers[i]->dumpFrameEvents(result);
3574 }
3575}
3576
Dan Stozae77c7662016-05-13 11:37:28 -07003577void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3578 result.append("Buffering stats:\n");
3579 result.append(" [Layer name] <Active time> <Two buffer> "
3580 "<Double buffered> <Triple buffered>\n");
3581 Mutex::Autolock lock(mBufferingStatsMutex);
3582 typedef std::tuple<std::string, float, float, float> BufferTuple;
3583 std::map<float, BufferTuple, std::greater<float>> sorted;
3584 for (const auto& statsPair : mBufferingStats) {
3585 const char* name = statsPair.first.c_str();
3586 const BufferingStats& stats = statsPair.second;
3587 if (stats.numSegments == 0) {
3588 continue;
3589 }
3590 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3591 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3592 stats.totalTime;
3593 float doubleBufferRatio = static_cast<float>(
3594 stats.doubleBufferedTime) / stats.totalTime;
3595 float tripleBufferRatio = static_cast<float>(
3596 stats.tripleBufferedTime) / stats.totalTime;
3597 sorted.insert({activeTime, {name, twoBufferRatio,
3598 doubleBufferRatio, tripleBufferRatio}});
3599 }
3600 for (const auto& sortedPair : sorted) {
3601 float activeTime = sortedPair.first;
3602 const BufferTuple& values = sortedPair.second;
3603 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3604 std::get<0>(values).c_str(), activeTime,
3605 std::get<1>(values), std::get<2>(values),
3606 std::get<3>(values));
3607 }
3608 result.append("\n");
3609}
3610
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003611void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3612 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3613
3614 // TODO: print out if wide-color mode is active or not
3615
3616 for (size_t d = 0; d < mDisplays.size(); d++) {
3617 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3618 int32_t hwcId = displayDevice->getHwcDisplayId();
3619 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3620 continue;
3621 }
3622
3623 result.appendFormat("Display %d color modes:\n", hwcId);
3624 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3625 for (auto&& mode : modes) {
3626 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3627 }
3628
3629 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3630 result.appendFormat(" Current color mode: %s (%d)\n",
3631 decodeColorMode(currentMode).c_str(), currentMode);
3632 }
3633 result.append("\n");
3634}
3635
Mathias Agopian74d211a2013-04-22 16:55:35 +02003636void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3637 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003638{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003639 bool colorize = false;
3640 if (index < args.size()
3641 && (args[index] == String16("--color"))) {
3642 colorize = true;
3643 index++;
3644 }
3645
3646 Colorizer colorizer(colorize);
3647
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003648 // figure out if we're stuck somewhere
3649 const nsecs_t now = systemTime();
3650 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3651 const nsecs_t inTransaction(mDebugInTransaction);
3652 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3653 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3654
3655 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003656 * Dump library configuration.
3657 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003658
3659 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003660 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003661 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003662 appendSfConfigString(result);
3663 appendUiConfigString(result);
3664 appendGuiConfigString(result);
3665 result.append("\n");
3666
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003667 result.append("\nWide-Color information:\n");
3668 dumpWideColorInfo(result);
3669
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003670 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003671 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003672 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003673 result.append(SyncFeatures::getInstance().toString());
3674 result.append("\n");
3675
Dan Stoza9e56aa02015-11-02 13:00:03 -08003676 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3677
Andy McFadden41d67d72014-04-25 16:58:34 -07003678 colorizer.bold(result);
3679 result.append("DispSync configuration: ");
3680 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003681 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003682 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003683 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003684 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003685 result.append("\n");
3686
Dan Stozab90cf072015-03-05 11:05:59 -08003687 // Dump static screen stats
3688 result.append("\n");
3689 dumpStaticScreenStats(result);
3690 result.append("\n");
3691
Dan Stozae77c7662016-05-13 11:37:28 -07003692 dumpBufferingStats(result);
3693
Andy McFadden4803b742012-09-24 19:07:20 -07003694 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003695 * Dump the visible layer list
3696 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003697 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003698 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003699 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003700 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003701 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003702 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003703
3704 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003705 * Dump Display state
3706 */
3707
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003708 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003709 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003710 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003711 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3712 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003713 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003714 }
3715
3716 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003717 * Dump SurfaceFlinger global state
3718 */
3719
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003720 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003721 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003722 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003723
Mathias Agopian888c8222012-08-04 21:10:38 -07003724 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003725 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003726
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003727 colorizer.bold(result);
3728 result.appendFormat("EGL implementation : %s\n",
3729 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3730 colorizer.reset(result);
3731 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003732 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003733
Mathias Agopian875d8e12013-06-07 15:35:48 -07003734 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003735
Mathias Agopian42977342012-08-05 00:40:46 -07003736 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003737 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3738 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003739 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003740 " last eglSwapBuffers() time: %f us\n"
3741 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003742 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003743 " refresh-rate : %f fps\n"
3744 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003745 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003746 " gpu_to_cpu_unsupported : %d\n"
3747 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003748 mLastSwapBufferTime/1000.0,
3749 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003750 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003751 1e9 / activeConfig->getVsyncPeriod(),
3752 activeConfig->getDpiX(),
3753 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003754 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003755
Mathias Agopian74d211a2013-04-22 16:55:35 +02003756 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003757 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003758
Mathias Agopian74d211a2013-04-22 16:55:35 +02003759 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003760 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003761
3762 /*
3763 * VSYNC state
3764 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003765 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003766 result.append("\n");
3767
3768 /*
3769 * HWC layer minidump
3770 */
3771 for (size_t d = 0; d < mDisplays.size(); d++) {
3772 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3773 int32_t hwcId = displayDevice->getHwcDisplayId();
3774 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3775 continue;
3776 }
3777
3778 result.appendFormat("Display %d HWC layers:\n", hwcId);
3779 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003780 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003781 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003782 });
Dan Stozae22aec72016-08-01 13:20:59 -07003783 result.append("\n");
3784 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003785
3786 /*
3787 * Dump HWComposer state
3788 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003789 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003790 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003791 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003792 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003793 result.appendFormat(" h/w composer %s\n",
3794 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003795 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003796
3797 /*
3798 * Dump gralloc state
3799 */
3800 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3801 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003802
3803 /*
3804 * Dump VrFlinger state if in use.
3805 */
3806 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3807 result.append("VrFlinger state:\n");
3808 result.append(mVrFlinger->Dump().c_str());
3809 result.append("\n");
3810 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003811}
3812
Mathias Agopian13127d82013-03-05 17:47:11 -08003813const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003814SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003815 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003816 wp<IBinder> dpy;
3817 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3818 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3819 dpy = mDisplays.keyAt(i);
3820 break;
3821 }
3822 }
3823 if (dpy == NULL) {
3824 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3825 // Just use the primary display so we have something to return
3826 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3827 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003828 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003829}
3830
Keun young Park63f165f2012-08-31 10:53:36 -07003831bool SurfaceFlinger::startDdmConnection()
3832{
3833 void* libddmconnection_dso =
3834 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3835 if (!libddmconnection_dso) {
3836 return false;
3837 }
3838 void (*DdmConnection_start)(const char* name);
3839 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003840 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003841 if (!DdmConnection_start) {
3842 dlclose(libddmconnection_dso);
3843 return false;
3844 }
3845 (*DdmConnection_start)(getServiceName());
3846 return true;
3847}
3848
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003849status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003850 switch (code) {
3851 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003852 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003853 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003854 case CLEAR_ANIMATION_FRAME_STATS:
3855 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003856 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003857 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003858 {
3859 // codes that require permission check
3860 IPCThreadState* ipc = IPCThreadState::self();
3861 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003862 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003863 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003864 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003865 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003866 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003867 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003868 break;
3869 }
Robert Carr1db73f62016-12-21 12:58:51 -08003870 /*
3871 * Calling setTransactionState is safe, because you need to have been
3872 * granted a reference to Client* and Handle* to do anything with it.
3873 *
3874 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3875 */
3876 case SET_TRANSACTION_STATE:
3877 case CREATE_SCOPED_CONNECTION:
3878 {
3879 return OK;
3880 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003881 case CAPTURE_SCREEN:
3882 {
3883 // codes that require permission check
3884 IPCThreadState* ipc = IPCThreadState::self();
3885 const int pid = ipc->getCallingPid();
3886 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003887 if ((uid != AID_GRAPHICS) &&
3888 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003889 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003890 return PERMISSION_DENIED;
3891 }
3892 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003893 }
3894 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003895 return OK;
3896}
3897
3898status_t SurfaceFlinger::onTransact(
3899 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3900{
3901 status_t credentialCheck = CheckTransactCodeCredentials(code);
3902 if (credentialCheck != OK) {
3903 return credentialCheck;
3904 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003905
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003906 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3907 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003908 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003909 IPCThreadState* ipc = IPCThreadState::self();
3910 const int uid = ipc->getCallingUid();
3911 if (CC_UNLIKELY(uid != AID_SYSTEM
3912 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003913 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003914 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003915 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003916 return PERMISSION_DENIED;
3917 }
3918 int n;
3919 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003920 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003921 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003922 return NO_ERROR;
3923 case 1002: // SHOW_UPDATES
3924 n = data.readInt32();
3925 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003926 invalidateHwcGeometry();
3927 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003929 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003930 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003931 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003933 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003934 setTransactionFlags(
3935 eTransactionNeeded|
3936 eDisplayTransactionNeeded|
3937 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003938 return NO_ERROR;
3939 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003940 case 1006:{ // send empty update
3941 signalRefresh();
3942 return NO_ERROR;
3943 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003944 case 1008: // toggle use of hw composer
3945 n = data.readInt32();
3946 mDebugDisableHWC = n ? 1 : 0;
3947 invalidateHwcGeometry();
3948 repaintEverything();
3949 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003950 case 1009: // toggle use of transform hint
3951 n = data.readInt32();
3952 mDebugDisableTransformHint = n ? 1 : 0;
3953 invalidateHwcGeometry();
3954 repaintEverything();
3955 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003956 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003957 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003958 reply->writeInt32(0);
3959 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003960 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003961 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003962 return NO_ERROR;
3963 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003964 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003965 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003966 return NO_ERROR;
3967 }
3968 case 1014: {
3969 // daltonize
3970 n = data.readInt32();
3971 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003972 case 1:
3973 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3974 break;
3975 case 2:
3976 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3977 break;
3978 case 3:
3979 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3980 break;
3981 default:
3982 mDaltonizer.setType(ColorBlindnessType::None);
3983 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003984 }
3985 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003986 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003987 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003988 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003989 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003990 invalidateHwcGeometry();
3991 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003992 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003993 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003994 case 1015: {
3995 // apply a color matrix
3996 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003997 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07003998 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07003999 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004000 for (size_t j = 0; j < 4; j++) {
4001 mColorMatrix[i][j] = data.readFloat();
4002 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004003 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004004 } else {
4005 mColorMatrix = mat4();
4006 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004007
4008 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4009 // the division by w in the fragment shader
4010 float4 lastRow(transpose(mColorMatrix)[3]);
4011 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4012 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4013 }
4014
Alan Viverette9c5a3332013-09-12 20:04:35 -07004015 invalidateHwcGeometry();
4016 repaintEverything();
4017 return NO_ERROR;
4018 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004019 // This is an experimental interface
4020 // Needs to be shifted to proper binder interface when we productize
4021 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004022 n = data.readInt32();
4023 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004024 return NO_ERROR;
4025 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004026 case 1017: {
4027 n = data.readInt32();
4028 mForceFullDamage = static_cast<bool>(n);
4029 return NO_ERROR;
4030 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004031 case 1018: { // Modify Choreographer's phase offset
4032 n = data.readInt32();
4033 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4034 return NO_ERROR;
4035 }
4036 case 1019: { // Modify SurfaceFlinger's phase offset
4037 n = data.readInt32();
4038 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4039 return NO_ERROR;
4040 }
Irvel468051e2016-06-13 16:44:44 -07004041 case 1020: { // Layer updates interceptor
4042 n = data.readInt32();
4043 if (n) {
4044 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004045 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004046 }
4047 else{
4048 ALOGV("Interceptor disabled");
4049 mInterceptor.disable();
4050 }
4051 return NO_ERROR;
4052 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004053 case 1021: { // Disable HWC virtual displays
4054 n = data.readInt32();
4055 mUseHwcVirtualDisplays = !n;
4056 return NO_ERROR;
4057 }
Romain Guy0147a172017-06-01 13:53:56 -07004058 case 1022: { // Set saturation boost
4059 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4060
4061 invalidateHwcGeometry();
4062 repaintEverything();
4063 return NO_ERROR;
4064 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004065 }
4066 }
4067 return err;
4068}
4069
Mathias Agopian53331da2011-08-22 21:44:41 -07004070void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004071 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004072 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004073}
4074
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004075// Checks that the requested width and height are valid and updates them to the display dimensions
4076// if they are set to 0
4077static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4078 Transform::orientation_flags rotation,
4079 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4080 // get screen geometry
4081 uint32_t displayWidth = displayDevice->getWidth();
4082 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004083
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004084 if (rotation & Transform::ROT_90) {
4085 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004086 }
4087
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004088 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4089 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4090 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4091 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004092 }
4093
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004094 if (*requestedWidth == 0) {
4095 *requestedWidth = displayWidth;
4096 }
4097 if (*requestedHeight == 0) {
4098 *requestedHeight = displayHeight;
4099 }
4100
4101 return NO_ERROR;
4102}
4103
4104// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4105class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004106public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004107 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4108 ~WindowDisconnector() {
4109 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004110 }
4111
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004112private:
4113 ANativeWindow* mWindow;
4114 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004115};
4116
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004117static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4118 uint32_t requestedHeight, bool hasWideColorDisplay,
4119 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4120 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4121 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4122
4123 int err = 0;
4124 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4125 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4126 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4127 err |= native_window_set_usage(window, usage);
4128
4129 if (hasWideColorDisplay) {
4130 err |= native_window_set_buffers_data_space(window,
4131 renderEngineUsesWideColor
4132 ? HAL_DATASPACE_DISPLAY_P3
4133 : HAL_DATASPACE_V0_SRGB);
4134 }
4135
4136 if (err != NO_ERROR) {
4137 return BAD_VALUE;
4138 }
4139
4140 /* TODO: Once we have the sync framework everywhere this can use
4141 * server-side waits on the fence that dequeueBuffer returns.
4142 */
4143 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4144 if (err != NO_ERROR) {
4145 return err;
4146 }
4147
4148 return NO_ERROR;
4149}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004150
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004151status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4152 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004153 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004154 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004155 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004156 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004157
4158 if (CC_UNLIKELY(display == 0))
4159 return BAD_VALUE;
4160
4161 if (CC_UNLIKELY(producer == 0))
4162 return BAD_VALUE;
4163
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004164 // if we have secure windows on this display, never allow the screen capture
4165 // unless the producer interface is local (i.e.: we can take a screenshot for
4166 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004167 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004168
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004169 // Convert to surfaceflinger's internal rotation type.
4170 Transform::orientation_flags rotationFlags;
4171 switch (rotation) {
4172 case ISurfaceComposer::eRotateNone:
4173 rotationFlags = Transform::ROT_0;
4174 break;
4175 case ISurfaceComposer::eRotate90:
4176 rotationFlags = Transform::ROT_90;
4177 break;
4178 case ISurfaceComposer::eRotate180:
4179 rotationFlags = Transform::ROT_180;
4180 break;
4181 case ISurfaceComposer::eRotate270:
4182 rotationFlags = Transform::ROT_270;
4183 break;
4184 default:
4185 rotationFlags = Transform::ROT_0;
4186 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4187 break;
4188 }
4189
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004190 { // Autolock scope
4191 Mutex::Autolock lock(mStateLock);
4192 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4193 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004194 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004195
4196 // create a surface (because we're a producer, and we need to
4197 // dequeue/queue a buffer)
4198 sp<Surface> surface = new Surface(producer, false);
4199
4200 // Put the screenshot Surface into async mode so that
4201 // Layer::headFenceHasSignaled will always return true and we'll latch the
4202 // first buffer regardless of whether or not its acquire fence has
4203 // signaled. This is needed to avoid a race condition in the rotation
4204 // animation. See b/30209608
4205 surface->setAsyncMode(true);
4206
4207 ANativeWindow* window = surface.get();
4208
4209 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4210 if (result != NO_ERROR) {
4211 return result;
4212 }
4213 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4214
4215 ANativeWindowBuffer* buffer = nullptr;
4216 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4217 getRenderEngine().usesWideColor(), &buffer);
4218 if (result != NO_ERROR) {
4219 return result;
4220 }
4221
4222 // This mutex protects syncFd and captureResult for communication of the return values from the
4223 // main thread back to this Binder thread
4224 std::mutex captureMutex;
4225 std::condition_variable captureCondition;
4226 std::unique_lock<std::mutex> captureLock(captureMutex);
4227 int syncFd = -1;
4228 std::optional<status_t> captureResult;
4229
4230 sp<LambdaMessage> message = new LambdaMessage([&]() {
4231 // If there is a refresh pending, bug out early and tell the binder thread to try again
4232 // after the refresh.
4233 if (mRefreshPending) {
4234 ATRACE_NAME("Skipping screenshot for now");
4235 std::unique_lock<std::mutex> captureLock(captureMutex);
4236 captureResult = std::make_optional<status_t>(EAGAIN);
4237 captureCondition.notify_one();
4238 return;
4239 }
4240
4241 status_t result = NO_ERROR;
4242 int fd = -1;
4243 {
4244 Mutex::Autolock _l(mStateLock);
4245 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4246 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4247 minLayerZ, maxLayerZ, useIdentityTransform,
4248 rotationFlags, isLocalScreenshot, &fd);
4249 }
4250
4251 {
4252 std::unique_lock<std::mutex> captureLock(captureMutex);
4253 syncFd = fd;
4254 captureResult = std::make_optional<status_t>(result);
4255 captureCondition.notify_one();
4256 }
4257 });
4258
4259 result = postMessageAsync(message);
4260 if (result == NO_ERROR) {
4261 captureCondition.wait(captureLock, [&]() { return captureResult; });
4262 while (*captureResult == EAGAIN) {
4263 captureResult.reset();
4264 result = postMessageAsync(message);
4265 if (result != NO_ERROR) {
4266 return result;
4267 }
4268 captureCondition.wait(captureLock, [&]() { return captureResult; });
4269 }
4270 result = *captureResult;
4271 }
4272
4273 if (result == NO_ERROR) {
4274 // queueBuffer takes ownership of syncFd
4275 result = window->queueBuffer(window, buffer, syncFd);
4276 }
4277
4278 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004279}
4280
Mathias Agopian180f10d2013-04-10 22:55:41 -07004281
4282void SurfaceFlinger::renderScreenImplLocked(
4283 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004284 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004285 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004286 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004287{
4288 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004289 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004290
4291 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004292 const int32_t hw_w = hw->getWidth();
4293 const int32_t hw_h = hw->getHeight();
4294 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004295 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004296
Dan Stozac1879002014-05-22 15:59:05 -07004297 // if a default or invalid sourceCrop is passed in, set reasonable values
4298 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4299 !sourceCrop.isValid()) {
4300 sourceCrop.setLeftTop(Point(0, 0));
4301 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4302 }
4303
4304 // ensure that sourceCrop is inside screen
4305 if (sourceCrop.left < 0) {
4306 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4307 }
Dan Stozabe31f442014-06-11 11:20:54 -07004308 if (sourceCrop.right > hw_w) {
4309 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004310 }
4311 if (sourceCrop.top < 0) {
4312 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4313 }
Dan Stozabe31f442014-06-11 11:20:54 -07004314 if (sourceCrop.bottom > hw_h) {
4315 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004316 }
4317
Romain Guy88d37dd2017-05-26 17:57:05 -07004318#ifdef USE_HWC2
4319 engine.setWideColor(hw->getWideColorSupport());
4320 engine.setColorMode(hw->getActiveColorMode());
4321#endif
4322
Mathias Agopian180f10d2013-04-10 22:55:41 -07004323 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004324 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004325
4326 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004327 engine.setViewportAndProjection(
4328 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004329 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004330
4331 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004332 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004333
Robert Carr1f0a16a2016-10-24 16:27:39 -07004334 // We loop through the first level of layers without traversing,
4335 // as we need to interpret min/max layer Z in the top level Z space.
4336 for (const auto& layer : mDrawingState.layersSortedByZ) {
4337 if (layer->getLayerStack() != hw->getLayerStack()) {
4338 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004339 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004340 const Layer::State& state(layer->getDrawingState());
4341 if (state.z < minLayerZ || state.z > maxLayerZ) {
4342 continue;
4343 }
Dan Stoza412903f2017-04-27 13:42:17 -07004344 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004345 if (!layer->isVisible()) {
4346 return;
4347 }
4348 if (filtering) layer->setFiltering(true);
4349 layer->draw(hw, useIdentityTransform);
4350 if (filtering) layer->setFiltering(false);
4351 });
4352 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004353
Mathias Agopian931bda12013-08-28 18:11:46 -07004354 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004355}
4356
Dan Stozaabcda352017-06-01 14:37:39 -07004357// A simple RAII class that holds an EGLImage and destroys it either:
4358// a) When the destroy() method is called
4359// b) When the object goes out of scope
4360class ImageHolder {
4361public:
4362 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4363 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004364
Dan Stozaabcda352017-06-01 14:37:39 -07004365 void destroy() {
4366 if (mImage != EGL_NO_IMAGE_KHR) {
4367 eglDestroyImageKHR(mDisplay, mImage);
4368 mImage = EGL_NO_IMAGE_KHR;
4369 }
4370 }
4371
4372private:
4373 const EGLDisplay mDisplay;
4374 EGLImageKHR mImage;
4375};
4376
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004377status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4378 ANativeWindowBuffer* buffer, Rect sourceCrop,
4379 uint32_t reqWidth, uint32_t reqHeight,
4380 int32_t minLayerZ, int32_t maxLayerZ,
4381 bool useIdentityTransform,
4382 Transform::orientation_flags rotation,
4383 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004384 ATRACE_CALL();
4385
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004386 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004387 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004388 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004389 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4390 (state.z < minLayerZ || state.z > maxLayerZ)) {
4391 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004392 }
Dan Stoza412903f2017-04-27 13:42:17 -07004393 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004394 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4395 layer->isSecure());
4396 });
4397 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004398
4399 if (!isLocalScreenshot && secureLayerIsVisible) {
4400 ALOGW("FB is protected: PERMISSION_DENIED");
4401 return PERMISSION_DENIED;
4402 }
4403
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004404 int syncFd = -1;
4405 // create an EGLImage from the buffer so we can later
4406 // turn it into a texture
4407 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4408 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4409 if (image == EGL_NO_IMAGE_KHR) {
4410 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004411 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004412
Dan Stozaabcda352017-06-01 14:37:39 -07004413 // This will automatically destroy the image if we return before calling its destroy method
4414 ImageHolder imageHolder(mEGLDisplay, image);
4415
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004416 // this binds the given EGLImage as a framebuffer for the
4417 // duration of this scope.
4418 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004419 if (imageBond.getStatus() != NO_ERROR) {
4420 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004421 return INVALID_OPERATION;
4422 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004423
Dan Stozaabcda352017-06-01 14:37:39 -07004424 // this will in fact render into our dequeued buffer
4425 // via an FBO, which means we didn't have to create
4426 // an EGLSurface and therefore we're not
4427 // dependent on the context's EGLConfig.
4428 renderScreenImplLocked(
4429 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4430 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004431
Dan Stozaabcda352017-06-01 14:37:39 -07004432 // Attempt to create a sync khr object that can produce a sync point. If that
4433 // isn't available, create a non-dupable sync object in the fallback path and
4434 // wait on it directly.
4435 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4436 if (!DEBUG_SCREENSHOTS) {
4437 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4438 // native fence fd will not be populated until flush() is done.
4439 getRenderEngine().flush();
4440 }
4441
4442 if (sync != EGL_NO_SYNC_KHR) {
4443 // get the sync fd
4444 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4445 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4446 ALOGW("captureScreen: failed to dup sync khr object");
4447 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004448 }
Dan Stozaabcda352017-06-01 14:37:39 -07004449 eglDestroySyncKHR(mEGLDisplay, sync);
4450 } else {
4451 // fallback path
4452 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004453 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004454 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4455 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4456 EGLint eglErr = eglGetError();
4457 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4458 ALOGW("captureScreen: fence wait timed out");
4459 } else {
4460 ALOGW_IF(eglErr != EGL_SUCCESS,
4461 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004462 }
4463 eglDestroySyncKHR(mEGLDisplay, sync);
4464 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004465 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004466 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004467 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004468 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004469
4470 if (DEBUG_SCREENSHOTS) {
4471 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4472 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4473 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4474 hw, minLayerZ, maxLayerZ);
4475 delete [] pixels;
4476 }
4477
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004478 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004479 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004480
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004481 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004482}
4483
Mathias Agopiand5556842013-09-19 17:08:37 -07004484void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004485 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004486 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004487 for (size_t y=0 ; y<h ; y++) {
4488 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4489 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004490 if (p[x] != 0xFF000000) return;
4491 }
4492 }
4493 ALOGE("*** we just took a black screenshot ***\n"
4494 "requested minz=%d, maxz=%d, layerStack=%d",
4495 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004496
Robert Carr2047fae2016-11-28 14:09:09 -08004497 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004498 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004499 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004500 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4501 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004502 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004503 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4504 layer->isVisible() ? '+' : '-',
4505 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004506 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004507 i++;
4508 });
4509 }
4510 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004511 }
4512}
4513
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004514// ---------------------------------------------------------------------------
4515
Dan Stoza412903f2017-04-27 13:42:17 -07004516void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4517 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004518}
4519
Dan Stoza412903f2017-04-27 13:42:17 -07004520void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4521 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004522}
4523
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004524}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004525
4526
4527#if defined(__gl_h_)
4528#error "don't include gl/gl.h in this file"
4529#endif
4530
4531#if defined(__gl2_h_)
4532#error "don't include gl2/gl2.h in this file"
4533#endif