blob: 63f260a9580e403fb8ddaa24dca63c17fc76b2bd [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
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800198 // debugging stuff...
199 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700200
Mathias Agopianb4b17302013-03-20 18:36:41 -0700201 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700202 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204 property_get("debug.sf.showupdates", value, "0");
205 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700206
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700207 property_get("debug.sf.ddms", value, "0");
208 mDebugDDMS = atoi(value);
209 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700210 if (!startDdmConnection()) {
211 // start failed, and DDMS debugging not enabled
212 mDebugDDMS = 0;
213 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700214 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700215 ALOGI_IF(mDebugRegion, "showupdates enabled");
216 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700217
218 property_get("debug.sf.disable_backpressure", value, "0");
219 mPropagateBackpressure = !atoi(value);
220 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700221
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800222 property_get("debug.sf.enable_hwc_vds", value, "0");
223 mUseHwcVirtualDisplays = atoi(value);
224 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800225
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800226 property_get("ro.sf.disable_triple_buffer", value, "1");
227 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800228 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700229
Romain Guy11d63f42017-07-20 12:47:14 -0700230 // We should be reading 'persist.sys.sf.color_saturation' here
231 // but since /data may be encrypted, we need to wait until after vold
232 // comes online to attempt to read the property. The property is
233 // instead read after the boot animation
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234}
235
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800236void SurfaceFlinger::onFirstRef()
237{
238 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800239}
240
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800241SurfaceFlinger::~SurfaceFlinger()
242{
Mathias Agopiana4912602012-07-12 14:25:33 -0700243 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
244 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
245 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800246}
247
Dan Stozac7014012014-02-14 15:03:43 -0800248void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800249{
250 // the window manager died on us. prepare its eulogy.
251
Andy McFadden13a082e2012-08-24 10:16:42 -0700252 // restore initial conditions (default device unblank, etc)
253 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800254
255 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700256 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800257}
258
Robert Carr1db73f62016-12-21 12:58:51 -0800259static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700260 status_t err = client->initCheck();
261 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800262 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800263 }
Robert Carr1db73f62016-12-21 12:58:51 -0800264 return nullptr;
265}
266
267sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
268 return initClient(new Client(this));
269}
270
271sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
272 const sp<IGraphicBufferProducer>& gbp) {
273 if (authenticateSurfaceTexture(gbp) == false) {
274 return nullptr;
275 }
276 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
277 if (layer == nullptr) {
278 return nullptr;
279 }
280
281 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282}
283
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700284sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
285 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700286{
287 class DisplayToken : public BBinder {
288 sp<SurfaceFlinger> flinger;
289 virtual ~DisplayToken() {
290 // no more references, this display must be terminated
291 Mutex::Autolock _l(flinger->mStateLock);
292 flinger->mCurrentState.displays.removeItem(this);
293 flinger->setTransactionFlags(eDisplayTransactionNeeded);
294 }
295 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700296 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700297 : flinger(flinger) {
298 }
299 };
300
301 sp<BBinder> token = new DisplayToken(this);
302
303 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700304 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700305 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700306 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700307 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700308 return token;
309}
310
Jesse Hall6c913be2013-08-08 12:15:49 -0700311void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
312 Mutex::Autolock _l(mStateLock);
313
314 ssize_t idx = mCurrentState.displays.indexOfKey(display);
315 if (idx < 0) {
316 ALOGW("destroyDisplay: invalid display token");
317 return;
318 }
319
320 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
321 if (!info.isVirtualDisplay()) {
322 ALOGE("destroyDisplay called for non-virtual display");
323 return;
324 }
Irvelffc9efc2016-07-27 15:16:37 -0700325 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700326 mCurrentState.displays.removeItemsAt(idx);
327 setTransactionFlags(eDisplayTransactionNeeded);
328}
329
Jesse Hall692c7232012-11-08 15:41:56 -0800330void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800331 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800332 ALOGW_IF(mBuiltinDisplays[type],
333 "Overwriting display token for display type %d", type);
334 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800335 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700336 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800337 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700338 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800339}
340
Mathias Agopiane57f2922012-08-09 16:29:12 -0700341sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700342 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700343 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
344 return NULL;
345 }
Jesse Hall692c7232012-11-08 15:41:56 -0800346 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700347}
348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349void SurfaceFlinger::bootFinished()
350{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700351 if (mStartPropertySetThread->join() != NO_ERROR) {
352 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 const nsecs_t now = systemTime();
355 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000356 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700357
358 // wait patiently for the window manager death
359 const String16 name("window");
360 sp<IBinder> window(defaultServiceManager()->getService(name));
361 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700362 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700363 }
364
Steven Thomas050b2c82017-03-06 11:45:16 -0800365 if (mVrFlinger) {
366 mVrFlinger->OnBootFinished();
367 }
368
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700369 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700370 // formerly we would just kill the process, but we now ask it to exit so it
371 // can choose where to stop the animation.
372 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700373
374 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
375 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
376 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700377
Romain Guyc53d3552017-07-20 18:49:46 -0700378 sp<LambdaMessage> bootFinished = new LambdaMessage([&]() {
379 mBootFinished = true;
380
Romain Guy11d63f42017-07-20 12:47:14 -0700381 readPersistentProperties();
Romain Guyc53d3552017-07-20 18:49:46 -0700382
383#ifdef USE_HWC2
384 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
385 if (hw->getWideColorSupport()) {
386 setActiveColorModeInternal(hw, HAL_COLOR_MODE_SRGB);
387 }
388#endif
Romain Guy11d63f42017-07-20 12:47:14 -0700389 });
Romain Guyc53d3552017-07-20 18:49:46 -0700390 postMessageAsync(bootFinished);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800391}
392
Mathias Agopian3f844832013-08-07 21:24:32 -0700393void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700394 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700395 RenderEngine& engine;
396 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700397 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700398 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
399 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700400 }
401 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700402 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700403 return true;
404 }
405 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700406 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700407}
408
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700409class DispSyncSource : public VSyncSource, private DispSync::Callback {
410public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700411 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000412 const char* name) :
413 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700414 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700415 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000416 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
417 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700418 mDispSync(dispSync),
419 mCallbackMutex(),
420 mCallback(),
421 mVsyncMutex(),
422 mPhaseOffset(phaseOffset),
423 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700424
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700425 virtual ~DispSyncSource() {}
426
427 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700428 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000430 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431 static_cast<DispSync::Callback*>(this));
432 if (err != NO_ERROR) {
433 ALOGE("error registering vsync callback: %s (%d)",
434 strerror(-err), err);
435 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700436 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700437 } else {
438 status_t err = mDispSync->removeEventListener(
439 static_cast<DispSync::Callback*>(this));
440 if (err != NO_ERROR) {
441 ALOGE("error unregistering vsync callback: %s (%d)",
442 strerror(-err), err);
443 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700444 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700445 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700446 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700447 }
448
449 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700450 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700451 mCallback = callback;
452 }
453
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700454 virtual void setPhaseOffset(nsecs_t phaseOffset) {
455 Mutex::Autolock lock(mVsyncMutex);
456
457 // Normalize phaseOffset to [0, period)
458 auto period = mDispSync->getPeriod();
459 phaseOffset %= period;
460 if (phaseOffset < 0) {
461 // If we're here, then phaseOffset is in (-period, 0). After this
462 // operation, it will be in (0, period)
463 phaseOffset += period;
464 }
465 mPhaseOffset = phaseOffset;
466
467 // If we're not enabled, we don't need to mess with the listeners
468 if (!mEnabled) {
469 return;
470 }
471
472 // Remove the listener with the old offset
473 status_t err = mDispSync->removeEventListener(
474 static_cast<DispSync::Callback*>(this));
475 if (err != NO_ERROR) {
476 ALOGE("error unregistering vsync callback: %s (%d)",
477 strerror(-err), err);
478 }
479
480 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000481 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700482 static_cast<DispSync::Callback*>(this));
483 if (err != NO_ERROR) {
484 ALOGE("error registering vsync callback: %s (%d)",
485 strerror(-err), err);
486 }
487 }
488
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700489private:
490 virtual void onDispSyncEvent(nsecs_t when) {
491 sp<VSyncSource::Callback> callback;
492 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700493 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700494 callback = mCallback;
495
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700496 if (mTraceVsync) {
497 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700498 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700499 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700500 }
501
502 if (callback != NULL) {
503 callback->onVSyncEvent(when);
504 }
505 }
506
Tim Murray4a4e4a22016-04-19 16:29:23 +0000507 const char* const mName;
508
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700509 int mValue;
510
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700511 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700512 const String8 mVsyncOnLabel;
513 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700514
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700515 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700516
517 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700519
520 Mutex mVsyncMutex; // Protects the following
521 nsecs_t mPhaseOffset;
522 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523};
524
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700525class InjectVSyncSource : public VSyncSource {
526public:
527 InjectVSyncSource() {}
528
529 virtual ~InjectVSyncSource() {}
530
531 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
532 std::lock_guard<std::mutex> lock(mCallbackMutex);
533 mCallback = callback;
534 }
535
536 virtual void onInjectSyncEvent(nsecs_t when) {
537 std::lock_guard<std::mutex> lock(mCallbackMutex);
538 mCallback->onVSyncEvent(when);
539 }
540
541 virtual void setVSyncEnabled(bool) {}
542 virtual void setPhaseOffset(nsecs_t) {}
543
544private:
545 std::mutex mCallbackMutex; // Protects the following
546 sp<VSyncSource::Callback> mCallback;
547};
548
Wei Wangf9b05ee2017-07-19 20:59:39 -0700549// Do not call property_set on main thread which will be blocked by init
550// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700551void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700552 ALOGI( "SurfaceFlinger's main thread ready to run. "
553 "Initializing graphics H/W...");
554
Romain Guyc53d3552017-07-20 18:49:46 -0700555 ALOGI("Phase offset NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900556
Dan Stoza9e56aa02015-11-02 13:00:03 -0800557 { // Autolock scope
558 Mutex::Autolock _l(mStateLock);
559
560 // initialize EGL for the default display
561 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
562 eglInitialize(mEGLDisplay, NULL, NULL);
563
564 // start the EventThread
565 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
566 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700567 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800568 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
569 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700570 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800571 mEventQueue.setEventThread(mSFEventThread);
572
Tim Murray22752852017-05-04 13:38:49 -0700573 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700574 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700575 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700576 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
577 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
578 }
Tim Murray22752852017-05-04 13:38:49 -0700579 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
580 ALOGE("Couldn't set SCHED_FIFO for EventThread");
581 }
Tim Murray41a38532016-06-22 12:42:10 -0700582
Dan Stoza9e56aa02015-11-02 13:00:03 -0800583 // Get a RenderEngine for the given display / config (can't fail)
584 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700585 HAL_PIXEL_FORMAT_RGBA_8888,
586 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800587 }
588
589 // Drop the state lock while we initialize the hardware composer. We drop
590 // the lock because on creation, it will call back into SurfaceFlinger to
591 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800592 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
593 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800594 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800595 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800596 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
597
Jesse Hall692c7232012-11-08 15:41:56 -0800598 Mutex::Autolock _l(mStateLock);
599
Steven Thomas050b2c82017-03-06 11:45:16 -0800600 if (useVrFlinger) {
601 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700602 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800603 mVrFlingerRequestsDisplay = requestDisplay;
604 signalTransaction();
605 };
606 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
607 vrFlingerRequestDisplayCallback);
608 if (!mVrFlinger) {
609 ALOGE("Failed to start vrflinger");
610 }
611 }
612
Mathias Agopian875d8e12013-06-07 15:35:48 -0700613 // retrieve the EGL context that was selected/created
614 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700615
Mathias Agopianda27af92012-09-13 18:17:13 -0700616 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
617 "couldn't create EGLContext");
618
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619 // make the GLContext current so that we can create textures when creating
620 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700621 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700622
Jamie Gennisd1700752013-10-14 12:22:52 -0700623 mEventControlThread = new EventControlThread(this);
624 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
625
Mathias Agopian92a979a2012-08-02 18:32:23 -0700626 // initialize our drawing state
627 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700628
Andy McFadden13a082e2012-08-24 10:16:42 -0700629 // set initial conditions (e.g. unblank default device)
630 initializeDisplays();
631
Dan Stoza4e637772016-07-28 13:31:51 -0700632 mRenderEngine->primeCache();
633
Wei Wangf9b05ee2017-07-19 20:59:39 -0700634 // Inform native graphics APIs whether the present timestamp is supported:
635 if (getHwComposer().hasCapability(
636 HWC2::Capability::PresentFenceIsNotReliable)) {
637 mStartPropertySetThread = new StartPropertySetThread(false);
638 } else {
639 mStartPropertySetThread = new StartPropertySetThread(true);
640 }
641
642 if (mStartPropertySetThread->Start() != NO_ERROR) {
643 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800644 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800645
Dan Stoza9e56aa02015-11-02 13:00:03 -0800646 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700647}
648
Romain Guy11d63f42017-07-20 12:47:14 -0700649void SurfaceFlinger::readPersistentProperties() {
650 char value[PROPERTY_VALUE_MAX];
651
652 property_get("persist.sys.sf.color_saturation", value, "1.0");
653 mSaturation = atof(value);
654 ALOGV("Saturation is set to %.2f", mSaturation);
655}
656
Mathias Agopiana67e4182012-06-19 17:26:12 -0700657void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800658 // Start boot animation service by setting a property mailbox
659 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700660 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800661 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700662 if (mStartPropertySetThread->join() != NO_ERROR) {
663 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800664 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700665}
666
Mathias Agopian875d8e12013-06-07 15:35:48 -0700667size_t SurfaceFlinger::getMaxTextureSize() const {
668 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700669}
670
Mathias Agopian875d8e12013-06-07 15:35:48 -0700671size_t SurfaceFlinger::getMaxViewportDims() const {
672 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700673}
674
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800675// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800676
Jamie Gennis582270d2011-08-17 18:19:00 -0700677bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800678 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800679 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800680 return authenticateSurfaceTextureLocked(bufferProducer);
681}
682
683bool SurfaceFlinger::authenticateSurfaceTextureLocked(
684 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800685 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700686 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800687}
688
Brian Anderson6b376712017-04-04 10:51:39 -0700689status_t SurfaceFlinger::getSupportedFrameTimestamps(
690 std::vector<FrameEvent>* outSupported) const {
691 *outSupported = {
692 FrameEvent::REQUESTED_PRESENT,
693 FrameEvent::ACQUIRE,
694 FrameEvent::LATCH,
695 FrameEvent::FIRST_REFRESH_START,
696 FrameEvent::LAST_REFRESH_START,
697 FrameEvent::GPU_COMPOSITION_DONE,
698 FrameEvent::DEQUEUE_READY,
699 FrameEvent::RELEASE,
700 };
701 if (!getHwComposer().hasCapability(
702 HWC2::Capability::PresentFenceIsNotReliable)) {
703 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
704 }
705 return NO_ERROR;
706}
707
Dan Stoza7f7da322014-05-02 15:26:25 -0700708status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
709 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700710 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700711 return BAD_VALUE;
712 }
713
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500714 if (!display.get())
715 return NAME_NOT_FOUND;
716
Jesse Hall692c7232012-11-08 15:41:56 -0800717 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700718 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800719 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700720 type = i;
721 break;
722 }
723 }
724
725 if (type < 0) {
726 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700727 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700728
Mathias Agopian8b736f12012-08-13 17:54:26 -0700729 // TODO: Not sure if display density should handled by SF any longer
730 class Density {
731 static int getDensityFromProperty(char const* propName) {
732 char property[PROPERTY_VALUE_MAX];
733 int density = 0;
734 if (property_get(propName, property, NULL) > 0) {
735 density = atoi(property);
736 }
737 return density;
738 }
739 public:
740 static int getEmuDensity() {
741 return getDensityFromProperty("qemu.sf.lcd_density"); }
742 static int getBuildDensity() {
743 return getDensityFromProperty("ro.sf.lcd_density"); }
744 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700745
Dan Stoza7f7da322014-05-02 15:26:25 -0700746 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700747
Dan Stoza9e56aa02015-11-02 13:00:03 -0800748 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700749 DisplayInfo info = DisplayInfo();
750
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751 float xdpi = hwConfig->getDpiX();
752 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700753
754 if (type == DisplayDevice::DISPLAY_PRIMARY) {
755 // The density of the device is provided by a build property
756 float density = Density::getBuildDensity() / 160.0f;
757 if (density == 0) {
758 // the build doesn't provide a density -- this is wrong!
759 // use xdpi instead
760 ALOGE("ro.sf.lcd_density must be defined as a build property");
761 density = xdpi / 160.0f;
762 }
763 if (Density::getEmuDensity()) {
764 // if "qemu.sf.lcd_density" is specified, it overrides everything
765 xdpi = ydpi = density = Density::getEmuDensity();
766 density /= 160.0f;
767 }
768 info.density = density;
769
770 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000771 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
772 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700773 } else {
774 // TODO: where should this value come from?
775 static const int TV_DENSITY = 213;
776 info.density = TV_DENSITY / 160.0f;
777 info.orientation = 0;
778 }
779
Dan Stoza9e56aa02015-11-02 13:00:03 -0800780 info.w = hwConfig->getWidth();
781 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700782 info.xdpi = xdpi;
783 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800784 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900785 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800786
Andy McFadden91b2ca82014-06-13 14:04:23 -0700787 // This is how far in advance a buffer must be queued for
788 // presentation at a given time. If you want a buffer to appear
789 // on the screen at time N, you must submit the buffer before
790 // (N - presentationDeadline).
791 //
792 // Normally it's one full refresh period (to give SF a chance to
793 // latch the buffer), but this can be reduced by configuring a
794 // DispSync offset. Any additional delays introduced by the hardware
795 // composer or panel must be accounted for here.
796 //
797 // We add an additional 1ms to allow for processing time and
798 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800799 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800800 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700801
802 // All non-virtual displays are currently considered secure.
803 info.secure = true;
804
Michael Wright28f24d02016-07-12 13:30:53 -0700805 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700806 }
807
Dan Stoza7f7da322014-05-02 15:26:25 -0700808 return NO_ERROR;
809}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700810
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800811status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700812 DisplayStatInfo* stats) {
813 if (stats == NULL) {
814 return BAD_VALUE;
815 }
816
817 // FIXME for now we always return stats for the primary display
818 memset(stats, 0, sizeof(*stats));
819 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
820 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
821 return NO_ERROR;
822}
823
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700824int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800825 if (display == NULL) {
826 ALOGE("%s : display is NULL", __func__);
827 return BAD_VALUE;
828 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700829
830 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700831 if (device != NULL) {
832 return device->getActiveConfig();
833 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700834
Dan Stoza24a42e92015-03-09 10:04:11 -0700835 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700836}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700837
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700838void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
839 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
840 this);
841 int32_t type = hw->getDisplayType();
842 int currentMode = hw->getActiveConfig();
843
844 if (mode == currentMode) {
845 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
846 return;
847 }
848
849 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
850 ALOGW("Trying to set config for virtual display");
851 return;
852 }
853
854 hw->setActiveConfig(mode);
855 getHwComposer().setActiveConfig(type, mode);
856}
857
858status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
859 class MessageSetActiveConfig: public MessageBase {
860 SurfaceFlinger& mFlinger;
861 sp<IBinder> mDisplay;
862 int mMode;
863 public:
864 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
865 int mode) :
866 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
867 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700868 Vector<DisplayInfo> configs;
869 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700870 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700871 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700872 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700873 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700874 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700875 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
876 if (hw == NULL) {
877 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700878 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700879 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
880 ALOGW("Attempt to set active config = %d for virtual display",
881 mMode);
882 } else {
883 mFlinger.setActiveConfigInternal(hw, mMode);
884 }
885 return true;
886 }
887 };
888 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
889 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700890 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700891}
Michael Wright28f24d02016-07-12 13:30:53 -0700892status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
893 Vector<android_color_mode_t>* outColorModes) {
894 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
895 return BAD_VALUE;
896 }
897
898 if (!display.get()) {
899 return NAME_NOT_FOUND;
900 }
901
902 int32_t type = NAME_NOT_FOUND;
903 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
904 if (display == mBuiltinDisplays[i]) {
905 type = i;
906 break;
907 }
908 }
909
910 if (type < 0) {
911 return type;
912 }
913
914 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
915 outColorModes->clear();
916 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
917
918 return NO_ERROR;
919}
920
921android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700922 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700923 if (device != nullptr) {
924 return device->getActiveColorMode();
925 }
926 return static_cast<android_color_mode_t>(BAD_VALUE);
927}
928
929void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
930 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700931 int32_t type = hw->getDisplayType();
932 android_color_mode_t currentMode = hw->getActiveColorMode();
933
934 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700935 return;
936 }
937
938 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
939 ALOGW("Trying to set config for virtual display");
940 return;
941 }
942
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600943 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
944 hw->getDisplayType());
945
Michael Wright28f24d02016-07-12 13:30:53 -0700946 hw->setActiveColorMode(mode);
947 getHwComposer().setActiveColorMode(type, mode);
948}
949
950
951status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
952 android_color_mode_t colorMode) {
953 class MessageSetActiveColorMode: public MessageBase {
954 SurfaceFlinger& mFlinger;
955 sp<IBinder> mDisplay;
956 android_color_mode_t mMode;
957 public:
958 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
959 android_color_mode_t mode) :
960 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
961 virtual bool handler() {
962 Vector<android_color_mode_t> modes;
963 mFlinger.getDisplayColorModes(mDisplay, &modes);
964 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
965 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600966 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
967 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700968 return true;
969 }
970 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
971 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600972 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
973 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700974 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600975 ALOGW("Attempt to set active color mode %s %d for virtual display",
976 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700977 } else {
978 mFlinger.setActiveColorModeInternal(hw, mMode);
979 }
980 return true;
981 }
982 };
983 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
984 postMessageSync(msg);
985 return NO_ERROR;
986}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700987
Svetoslavd85084b2014-03-20 10:28:31 -0700988status_t SurfaceFlinger::clearAnimationFrameStats() {
989 Mutex::Autolock _l(mStateLock);
990 mAnimFrameTracker.clearStats();
991 return NO_ERROR;
992}
993
994status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
995 Mutex::Autolock _l(mStateLock);
996 mAnimFrameTracker.getStats(outStats);
997 return NO_ERROR;
998}
999
Dan Stozac4f471e2016-03-24 09:31:08 -07001000status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1001 HdrCapabilities* outCapabilities) const {
1002 Mutex::Autolock _l(mStateLock);
1003
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001004 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001005 if (displayDevice == nullptr) {
1006 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1007 return BAD_VALUE;
1008 }
1009
1010 std::unique_ptr<HdrCapabilities> capabilities =
1011 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1012 if (capabilities) {
1013 std::swap(*outCapabilities, *capabilities);
1014 } else {
1015 return BAD_VALUE;
1016 }
1017
1018 return NO_ERROR;
1019}
1020
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001021status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1022 if (enable == mInjectVSyncs) {
1023 return NO_ERROR;
1024 }
1025
1026 if (enable) {
1027 mInjectVSyncs = enable;
1028 ALOGV("VSync Injections enabled");
1029 if (mVSyncInjector.get() == nullptr) {
1030 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001031 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001032 }
1033 mEventQueue.setEventThread(mInjectorEventThread);
1034 } else {
1035 mInjectVSyncs = enable;
1036 ALOGV("VSync Injections disabled");
1037 mEventQueue.setEventThread(mSFEventThread);
1038 mVSyncInjector.clear();
1039 }
1040 return NO_ERROR;
1041}
1042
1043status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1044 if (!mInjectVSyncs) {
1045 ALOGE("VSync Injections not enabled");
1046 return BAD_VALUE;
1047 }
1048 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1049 ALOGV("Injecting VSync inside SurfaceFlinger");
1050 mVSyncInjector->onInjectSyncEvent(when);
1051 }
1052 return NO_ERROR;
1053}
1054
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001055// ----------------------------------------------------------------------------
1056
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001057sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1058 ISurfaceComposer::VsyncSource vsyncSource) {
1059 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1060 return mSFEventThread->createEventConnection();
1061 } else {
1062 return mEventThread->createEventConnection();
1063 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001064}
1065
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001066// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001067
1068void SurfaceFlinger::waitForEvent() {
1069 mEventQueue.waitMessage();
1070}
1071
1072void SurfaceFlinger::signalTransaction() {
1073 mEventQueue.invalidate();
1074}
1075
1076void SurfaceFlinger::signalLayerUpdate() {
1077 mEventQueue.invalidate();
1078}
1079
1080void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001081 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001082 mEventQueue.refresh();
1083}
1084
1085status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001086 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001087 return mEventQueue.postMessage(msg, reltime);
1088}
1089
1090status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001091 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001092 status_t res = mEventQueue.postMessage(msg, reltime);
1093 if (res == NO_ERROR) {
1094 msg->wait();
1095 }
1096 return res;
1097}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001098
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001099void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001100 do {
1101 waitForEvent();
1102 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001103}
1104
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001105void SurfaceFlinger::enableHardwareVsync() {
1106 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001107 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001108 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001109 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1110 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001111 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001112 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001113}
1114
Jesse Hall948fe0c2013-10-14 12:56:09 -07001115void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001116 Mutex::Autolock _l(mHWVsyncLock);
1117
Jesse Hall948fe0c2013-10-14 12:56:09 -07001118 if (makeAvailable) {
1119 mHWVsyncAvailable = true;
1120 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001121 // Hardware vsync is not currently available, so abort the resync
1122 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001123 return;
1124 }
1125
Dan Stoza9e56aa02015-11-02 13:00:03 -08001126 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1127 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001128
1129 mPrimaryDispSync.reset();
1130 mPrimaryDispSync.setPeriod(period);
1131
1132 if (!mPrimaryHWVsyncEnabled) {
1133 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001134 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1135 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001136 mPrimaryHWVsyncEnabled = true;
1137 }
1138}
1139
Jesse Hall948fe0c2013-10-14 12:56:09 -07001140void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001141 Mutex::Autolock _l(mHWVsyncLock);
1142 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001143 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1144 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001145 mPrimaryDispSync.endResync();
1146 mPrimaryHWVsyncEnabled = false;
1147 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001148 if (makeUnavailable) {
1149 mHWVsyncAvailable = false;
1150 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001151}
1152
Tim Murray4a4e4a22016-04-19 16:29:23 +00001153void SurfaceFlinger::resyncWithRateLimit() {
1154 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001155
1156 // No explicit locking is needed here since EventThread holds a lock while calling this method
1157 static nsecs_t sLastResyncAttempted = 0;
1158 const nsecs_t now = systemTime();
1159 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001160 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001161 }
Dan Stoza57164302017-05-08 14:03:54 -07001162 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001163}
1164
Steven Thomas3cfac282017-02-06 12:29:30 -08001165void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1166 nsecs_t timestamp) {
1167 Mutex::Autolock lock(mStateLock);
1168 // Ignore any vsyncs from the non-active hardware composer.
1169 if (composer != mHwc) {
1170 return;
1171 }
1172
Jamie Gennisd1700752013-10-14 12:22:52 -07001173 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001174
Jamie Gennisd1700752013-10-14 12:22:52 -07001175 { // Scope for the lock
1176 Mutex::Autolock _l(mHWVsyncLock);
1177 if (type == 0 && mPrimaryHWVsyncEnabled) {
1178 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001179 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001180 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001181
1182 if (needsHwVsync) {
1183 enableHardwareVsync();
1184 } else {
1185 disableHardwareVsync(false);
1186 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001187}
1188
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001189void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001190 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001191 *compositorTiming = mCompositorTiming;
1192}
1193
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001194void SurfaceFlinger::createDefaultDisplayDevice() {
1195 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1196 wp<IBinder> token = mBuiltinDisplays[type];
1197
1198 // All non-virtual displays are currently considered secure.
1199 const bool isSecure = true;
1200
1201 sp<IGraphicBufferProducer> producer;
1202 sp<IGraphicBufferConsumer> consumer;
1203 BufferQueue::createBufferQueue(&producer, &consumer);
1204
1205 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1206
1207 bool hasWideColorModes = false;
1208 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1209 for (android_color_mode_t colorMode : modes) {
1210 switch (colorMode) {
1211 case HAL_COLOR_MODE_DISPLAY_P3:
1212 case HAL_COLOR_MODE_ADOBE_RGB:
1213 case HAL_COLOR_MODE_DCI_P3:
1214 hasWideColorModes = true;
1215 break;
1216 default:
1217 break;
1218 }
1219 }
1220 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1221 token, fbs, producer, mRenderEngine->getEGLConfig(),
1222 hasWideColorModes && hasWideColorDisplay);
1223 mDisplays.add(token, hw);
Romain Guyc53d3552017-07-20 18:49:46 -07001224 setActiveColorModeInternal(hw, HAL_COLOR_MODE_NATIVE);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001225}
1226
1227void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001228 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001229
1230 if (composer->isUsingVrComposer()) {
1231 // We handle initializing the primary display device for the VR
1232 // window manager hwc explicitly at the time of transition.
1233 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1234 ALOGE("External displays are not supported by the vr hardware composer.");
1235 }
1236 return;
1237 }
1238
Dan Stoza9e56aa02015-11-02 13:00:03 -08001239 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1240 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001241 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1242 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001243 } else {
1244 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001245 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001246 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001247 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001248 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001249 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1250 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001251 }
1252 setTransactionFlags(eDisplayTransactionNeeded);
1253
Andy McFadden9e9689c2012-10-10 18:17:51 -07001254 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001255 }
Mathias Agopian86303202012-07-24 22:46:10 -07001256}
1257
Steven Thomas3cfac282017-02-06 12:29:30 -08001258void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1259 Mutex::Autolock lock(mStateLock);
1260 if (composer == mHwc) {
1261 repaintEverything();
1262 } else {
1263 // This isn't from our current hardware composer. If it's a callback
1264 // from the real composer, forward the refresh request to vr
1265 // flinger. Otherwise ignore it.
1266 if (!composer->isUsingVrComposer()) {
1267 mVrFlinger->OnHardwareComposerRefresh();
1268 }
1269 }
1270}
1271
Dan Stoza9e56aa02015-11-02 13:00:03 -08001272void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001274 getHwComposer().setVsyncEnabled(disp,
1275 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001276}
1277
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001278// Note: it is assumed the caller holds |mStateLock| when this is called
1279void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001280 disableHardwareVsync(true);
1281 clearHwcLayers(mDrawingState.layersSortedByZ);
1282 clearHwcLayers(mCurrentState.layersSortedByZ);
Steven Thomasf5a5f6e2017-07-17 13:59:23 -07001283 for (size_t disp = 0; disp < mDisplays.size(); ++disp) {
1284 clearHwcLayers(mDisplays[disp]->getVisibleLayersSortedByZ());
1285 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001286 // Clear the drawing state so that the logic inside of
1287 // handleTransactionLocked will fire. It will determine the delta between
1288 // mCurrentState and mDrawingState and re-apply all changes when we make the
1289 // transition.
1290 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001291 // Release virtual display hwcId during vr mode transition.
1292 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1293 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1294 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1295 displayDevice->disconnect(getHwComposer());
1296 }
1297 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001298 mDisplays.clear();
1299}
1300
Steven Thomas050b2c82017-03-06 11:45:16 -08001301void SurfaceFlinger::updateVrFlinger() {
1302 if (!mVrFlinger)
1303 return;
1304 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1305 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001306 return;
1307 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001308
Steven Thomas050b2c82017-03-06 11:45:16 -08001309 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001310 // Construct new HWComposer without holding any locks.
1311 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001312
1313 // Set up the event handlers. This step is neccessary to initialize the internal state of
1314 // the hardware composer object properly. Our callbacks are designed such that if they are
1315 // triggered between now and the point where the display is properly re-initialized, they
1316 // will not have any effect, so this is safe to do here, before the lock is aquired.
1317 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001318 ALOGV("Vr HWC created");
1319 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001320
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001321 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001322
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001323 if (vrFlingerRequestsDisplay) {
1324 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001325
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001326 mHwc = mVrHwc;
1327 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001328
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001329 } else {
1330 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001331
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001332 resetHwcLocked();
1333
1334 mHwc = mRealHwc;
1335 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001336 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001337
1338 mVisibleRegionsDirty = true;
1339 invalidateHwcGeometry();
1340
1341 // Explicitly re-initialize the primary display. This is because some other
1342 // parts of this class rely on the primary display always being available.
1343 createDefaultDisplayDevice();
1344
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001345 // Re-enable default display.
1346 sp<LambdaMessage> requestMessage = new LambdaMessage([&]() {
1347 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1348 setPowerModeInternal(hw, HWC_POWER_MODE_NORMAL);
1349
1350 // Reset the timing values to account for the period of the swapped in HWC
1351 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1352 const nsecs_t period = activeConfig->getVsyncPeriod();
1353 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1354
1355 // Use phase of 0 since phase is not known.
1356 // Use latency of 0, which will snap to the ideal latency.
1357 setCompositorTimingSnapped(0, period, 0);
1358 });
1359 postMessageAsync(requestMessage);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001360
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001361 android_atomic_or(1, &mRepaintEverything);
1362 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001363}
1364
Mathias Agopian4fec8732012-06-29 14:12:52 -07001365void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001366 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001367 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001368 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001369 bool frameMissed = !mHadClientComposition &&
1370 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001371 (mPreviousPresentFence->getSignalTime() ==
1372 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001373 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001374 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001375 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001376 signalLayerUpdate();
1377 break;
1378 }
1379
Steven Thomas050b2c82017-03-06 11:45:16 -08001380 // Now that we're going to make it to the handleMessageTransaction()
1381 // call below it's safe to call updateVrFlinger(), which will
1382 // potentially trigger a display handoff.
1383 updateVrFlinger();
1384
Dan Stoza6b9454d2014-11-07 16:00:59 -08001385 bool refreshNeeded = handleMessageTransaction();
1386 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001387 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001388 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001389 // Signal a refresh if a transaction modified the window state,
1390 // a new buffer was latched, or if HWC has requested a full
1391 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001392 signalRefresh();
1393 }
1394 break;
1395 }
1396 case MessageQueue::REFRESH: {
1397 handleMessageRefresh();
1398 break;
1399 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001400 }
1401}
1402
Dan Stoza6b9454d2014-11-07 16:00:59 -08001403bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001404 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001405 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001406 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001407 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001408 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001409 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001410}
1411
Dan Stoza6b9454d2014-11-07 16:00:59 -08001412bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001413 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001414 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001415}
1416
1417void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001418 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001419
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001420 mRefreshPending = false;
1421
Pablo Ceballos40845df2016-01-25 17:41:15 -08001422 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001423
Brian Andersond6927fb2016-07-23 23:37:30 -07001424 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001425 rebuildLayerStacks();
1426 setUpHWComposer();
1427 doDebugFlashRegions();
1428 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001429 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001430
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001431 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001432
1433 mHadClientComposition = false;
1434 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1435 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1436 mHadClientComposition = mHadClientComposition ||
1437 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1438 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001439
Dan Stoza9e56aa02015-11-02 13:00:03 -08001440 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001441}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001442
Mathias Agopiancd60f992012-08-16 16:28:27 -07001443void SurfaceFlinger::doDebugFlashRegions()
1444{
1445 // is debugging enabled
1446 if (CC_LIKELY(!mDebugRegion))
1447 return;
1448
1449 const bool repaintEverything = mRepaintEverything;
1450 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1451 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001452 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001453 // transform the dirty region into this screen's coordinate space
1454 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1455 if (!dirtyRegion.isEmpty()) {
1456 // redraw the whole screen
1457 doComposeSurfaces(hw, Region(hw->bounds()));
1458
1459 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001460 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001461 RenderEngine& engine(getRenderEngine());
1462 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1463
Mathias Agopianda27af92012-09-13 18:17:13 -07001464 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001465 }
1466 }
1467 }
1468
1469 postFramebuffer();
1470
1471 if (mDebugRegion > 1) {
1472 usleep(mDebugRegion * 1000);
1473 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001474
Dan Stoza9e56aa02015-11-02 13:00:03 -08001475 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001476 auto& displayDevice = mDisplays[displayId];
1477 if (!displayDevice->isDisplayOn()) {
1478 continue;
1479 }
1480
1481 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001482 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1483 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001484 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001485}
1486
Brian Andersond6927fb2016-07-23 23:37:30 -07001487void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001488{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001489 ATRACE_CALL();
1490 ALOGV("preComposition");
1491
Mathias Agopiancd60f992012-08-16 16:28:27 -07001492 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001493 mDrawingState.traverseInZOrder([&](Layer* layer) {
1494 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001495 needExtraInvalidate = true;
1496 }
Robert Carr2047fae2016-11-28 14:09:09 -08001497 });
1498
Mathias Agopiancd60f992012-08-16 16:28:27 -07001499 if (needExtraInvalidate) {
1500 signalLayerUpdate();
1501 }
1502}
1503
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001504void SurfaceFlinger::updateCompositorTiming(
1505 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1506 std::shared_ptr<FenceTime>& presentFenceTime) {
1507 // Update queue of past composite+present times and determine the
1508 // most recently known composite to present latency.
1509 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1510 nsecs_t compositeToPresentLatency = -1;
1511 while (!mCompositePresentTimes.empty()) {
1512 CompositePresentTime& cpt = mCompositePresentTimes.front();
1513 // Cached values should have been updated before calling this method,
1514 // which helps avoid duplicate syscalls.
1515 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1516 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1517 break;
1518 }
1519 compositeToPresentLatency = displayTime - cpt.composite;
1520 mCompositePresentTimes.pop();
1521 }
1522
1523 // Don't let mCompositePresentTimes grow unbounded, just in case.
1524 while (mCompositePresentTimes.size() > 16) {
1525 mCompositePresentTimes.pop();
1526 }
1527
Brian Andersond0010582017-03-07 13:20:31 -08001528 setCompositorTimingSnapped(
1529 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1530}
1531
1532void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1533 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001534 // Integer division and modulo round toward 0 not -inf, so we need to
1535 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001536 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001537 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1538 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1539
Brian Andersond0010582017-03-07 13:20:31 -08001540 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1541 if (idealLatency <= 0) {
1542 idealLatency = vsyncInterval;
1543 }
1544
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001545 // Snap the latency to a value that removes scheduling jitter from the
1546 // composition and present times, which often have >1ms of jitter.
1547 // Reducing jitter is important if an app attempts to extrapolate
1548 // something (such as user input) to an accurate diasplay time.
1549 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1550 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001551 nsecs_t bias = vsyncInterval / 2;
1552 int64_t extraVsyncs =
1553 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1554 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1555 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001556
Brian Andersond0010582017-03-07 13:20:31 -08001557 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001558 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1559 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001560 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001561}
1562
1563void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001564{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001565 ATRACE_CALL();
1566 ALOGV("postComposition");
1567
Brian Anderson3546a3f2016-07-14 11:51:14 -07001568 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001569 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001570 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001571 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001572 }
1573
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001574 // |mStateLock| not needed as we are on the main thread
1575 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001576
1577 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1578 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1579 glCompositionDoneFenceTime =
1580 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1581 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1582 } else {
1583 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1584 }
1585 mGlCompositionDoneTimeline.updateSignalTimes();
1586
Brian Anderson4e606e32017-03-16 15:34:57 -07001587 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1588 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1589 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001590 mDisplayTimeline.updateSignalTimes();
1591
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001592 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1593 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1594
1595 // We use the refreshStartTime which might be sampled a little later than
1596 // when we started doing work for this frame, but that should be okay
1597 // since updateCompositorTiming has snapping logic.
1598 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001599 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001600 CompositorTiming compositorTiming;
1601 {
1602 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1603 compositorTiming = mCompositorTiming;
1604 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001605
Robert Carr2047fae2016-11-28 14:09:09 -08001606 mDrawingState.traverseInZOrder([&](Layer* layer) {
1607 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001608 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001609 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001610 recordBufferingStats(layer->getName().string(),
1611 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001612 }
Robert Carr2047fae2016-11-28 14:09:09 -08001613 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001614
Brian Anderson4e606e32017-03-16 15:34:57 -07001615 if (presentFence->isValid()) {
1616 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001617 enableHardwareVsync();
1618 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001619 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001620 }
1621 }
1622
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001623 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001624 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001625 enableHardwareVsync();
1626 }
1627 }
1628
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001629 if (mAnimCompositionPending) {
1630 mAnimCompositionPending = false;
1631
Brian Anderson4e606e32017-03-16 15:34:57 -07001632 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001633 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001634 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001635 } else {
1636 // The HWC doesn't support present fences, so use the refresh
1637 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001638 nsecs_t presentTime =
1639 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001640 mAnimFrameTracker.setActualPresentTime(presentTime);
1641 }
1642 mAnimFrameTracker.advanceFrame();
1643 }
Dan Stozab90cf072015-03-05 11:05:59 -08001644
1645 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1646 return;
1647 }
1648
1649 nsecs_t currentTime = systemTime();
1650 if (mHasPoweredOff) {
1651 mHasPoweredOff = false;
1652 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001653 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001654 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001655 if (numPeriods < NUM_BUCKETS - 1) {
1656 mFrameBuckets[numPeriods] += elapsedTime;
1657 } else {
1658 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1659 }
1660 mTotalTime += elapsedTime;
1661 }
1662 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001663}
1664
1665void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001666 ATRACE_CALL();
1667 ALOGV("rebuildLayerStacks");
1668
Mathias Agopiancd60f992012-08-16 16:28:27 -07001669 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001670 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1671 ATRACE_CALL();
1672 mVisibleRegionsDirty = false;
1673 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001674
Jeff Sharkey76488112017-02-27 14:15:18 -07001675 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1676 Region opaqueRegion;
1677 Region dirtyRegion;
1678 Vector<sp<Layer>> layersSortedByZ;
1679 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1680 const Transform& tr(displayDevice->getTransform());
1681 const Rect bounds(displayDevice->getBounds());
1682 if (displayDevice->isDisplayOn()) {
1683 computeVisibleRegions(
1684 displayDevice->getLayerStack(), dirtyRegion,
1685 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001686
Jeff Sharkey76488112017-02-27 14:15:18 -07001687 mDrawingState.traverseInZOrder([&](Layer* layer) {
1688 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1689 Region drawRegion(tr.transform(
1690 layer->visibleNonTransparentRegion));
1691 drawRegion.andSelf(bounds);
1692 if (!drawRegion.isEmpty()) {
1693 layersSortedByZ.add(layer);
1694 } else {
1695 // Clear out the HWC layer if this layer was
1696 // previously visible, but no longer is
1697 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1698 nullptr);
1699 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001700 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001701 // WM changes displayDevice->layerStack upon sleep/awake.
1702 // Here we make sure we delete the HWC layers even if
1703 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001704 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1705 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001706 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001707 });
1708 }
1709 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1710 displayDevice->undefinedRegion.set(bounds);
1711 displayDevice->undefinedRegion.subtractSelf(
1712 tr.transform(opaqueRegion));
1713 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001714 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001715 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001716}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001717
Romain Guy0147a172017-06-01 13:53:56 -07001718mat4 SurfaceFlinger::computeSaturationMatrix() const {
1719 if (mSaturation == 1.0f) {
1720 return mat4();
1721 }
1722
1723 // Rec.709 luma coefficients
1724 float3 luminance{0.213f, 0.715f, 0.072f};
1725 luminance *= 1.0f - mSaturation;
1726 return mat4(
1727 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1728 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1729 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1730 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1731 );
1732}
1733
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001734// pickColorMode translates a given dataspace into the best available color mode.
1735// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001736android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001737 switch (dataSpace) {
1738 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1739 // system expects.
1740 case HAL_DATASPACE_UNKNOWN:
1741 case HAL_DATASPACE_SRGB:
1742 case HAL_DATASPACE_V0_SRGB:
1743 return HAL_COLOR_MODE_SRGB;
1744 break;
1745
1746 case HAL_DATASPACE_DISPLAY_P3:
1747 return HAL_COLOR_MODE_DISPLAY_P3;
1748 break;
1749
1750 default:
1751 // TODO (courtneygo): Do we want to assert an error here?
1752 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1753 dataSpace);
1754 return HAL_COLOR_MODE_SRGB;
1755 break;
1756 }
1757}
1758
Romain Guy0147a172017-06-01 13:53:56 -07001759android_dataspace SurfaceFlinger::bestTargetDataSpace(
1760 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001761 // Only support sRGB and Display-P3 right now.
1762 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1763 return HAL_DATASPACE_DISPLAY_P3;
1764 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001765 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1766 return HAL_DATASPACE_DISPLAY_P3;
1767 }
1768 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1769 return HAL_DATASPACE_DISPLAY_P3;
1770 }
1771
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001772 return HAL_DATASPACE_V0_SRGB;
1773}
1774
Mathias Agopiancd60f992012-08-16 16:28:27 -07001775void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001776 ATRACE_CALL();
1777 ALOGV("setUpHWComposer");
1778
Jesse Hall028dc8f2013-08-20 16:35:32 -07001779 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001780 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1781 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1782 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1783
1784 // If nothing has changed (!dirty), don't recompose.
1785 // If something changed, but we don't currently have any visible layers,
1786 // and didn't when we last did a composition, then skip it this time.
1787 // The second rule does two things:
1788 // - When all layers are removed from a display, we'll emit one black
1789 // frame, then nothing more until we get new layers.
1790 // - When a display is created with a private layer stack, we won't
1791 // emit any black frames until a layer is added to the layer stack.
1792 bool mustRecompose = dirty && !(empty && wasEmpty);
1793
1794 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1795 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1796 mustRecompose ? "doing" : "skipping",
1797 dirty ? "+" : "-",
1798 empty ? "+" : "-",
1799 wasEmpty ? "+" : "-");
1800
Dan Stoza71433162014-02-04 16:22:36 -08001801 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001802
1803 if (mustRecompose) {
1804 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1805 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001806 }
1807
Dan Stoza9e56aa02015-11-02 13:00:03 -08001808 // build the h/w work list
1809 if (CC_UNLIKELY(mGeometryInvalid)) {
1810 mGeometryInvalid = false;
1811 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1812 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1813 const auto hwcId = displayDevice->getHwcDisplayId();
1814 if (hwcId >= 0) {
1815 const Vector<sp<Layer>>& currentLayers(
1816 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001817 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001818 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001819 if (!layer->hasHwcLayer(hwcId)) {
1820 auto hwcLayer = mHwc->createLayer(hwcId);
1821 if (hwcLayer) {
1822 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1823 } else {
1824 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001825 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001826 }
1827 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001828
Robert Carrae060832016-11-28 10:51:00 -08001829 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001830 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001831 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001832 }
1833 }
1834 }
1835 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001836 }
Riley Andrews03414a12014-07-01 14:22:59 -07001837
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001838
Romain Guy0147a172017-06-01 13:53:56 -07001839 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001840
Dan Stoza9e56aa02015-11-02 13:00:03 -08001841 // Set the per-frame data
1842 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1843 auto& displayDevice = mDisplays[displayId];
1844 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001845
Dan Stoza9e56aa02015-11-02 13:00:03 -08001846 if (hwcId < 0) {
1847 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001848 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001849 if (colorMatrix != mPreviousColorMatrix) {
1850 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1851 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1852 "display %zd: %d", displayId, result);
1853 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001854 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1855 layer->setPerFrameData(displayDevice);
1856 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001857
1858 if (hasWideColorDisplay) {
1859 android_color_mode newColorMode;
1860 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1861
1862 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1863 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1864 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1865 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1866 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1867 }
1868 newColorMode = pickColorMode(newDataSpace);
1869
Romain Guyc53d3552017-07-20 18:49:46 -07001870 // We want the color mode of the boot animation to match that of the bootloader
1871 // To achieve this we suppress color mode changes until after the boot animation
1872 if (mBootFinished) {
1873 setActiveColorModeInternal(displayDevice, newColorMode);
1874 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001875 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001876 }
1877
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001878 mPreviousColorMatrix = colorMatrix;
1879
Dan Stoza9e56aa02015-11-02 13:00:03 -08001880 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001881 auto& displayDevice = mDisplays[displayId];
1882 if (!displayDevice->isDisplayOn()) {
1883 continue;
1884 }
1885
1886 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001887 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1888 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001889 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001890}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001891
Mathias Agopiancd60f992012-08-16 16:28:27 -07001892void SurfaceFlinger::doComposition() {
1893 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001894 ALOGV("doComposition");
1895
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001896 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001897 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001898 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001899 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001900 // transform the dirty region into this screen's coordinate space
1901 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001902
1903 // repaint the framebuffer (if needed)
1904 doDisplayComposition(hw, dirtyRegion);
1905
Mathias Agopiancd60f992012-08-16 16:28:27 -07001906 hw->dirtyRegion.clear();
1907 hw->flip(hw->swapRegion);
1908 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001909 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001910 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001911 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001912}
1913
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001914void SurfaceFlinger::postFramebuffer()
1915{
Mathias Agopian841cde52012-03-01 15:44:37 -08001916 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001917 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001918
Mathias Agopiana44b0412011-10-16 18:46:35 -07001919 const nsecs_t now = systemTime();
1920 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001921
Dan Stoza9e56aa02015-11-02 13:00:03 -08001922 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1923 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001924 if (!displayDevice->isDisplayOn()) {
1925 continue;
1926 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001927 const auto hwcId = displayDevice->getHwcDisplayId();
1928 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001929 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001930 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001931 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001932 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1934 sp<Fence> releaseFence = Fence::NO_FENCE;
1935 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1936 releaseFence = displayDevice->getClientTargetAcquireFence();
1937 } else {
1938 auto hwcLayer = layer->getHwcLayer(hwcId);
1939 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001940 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001941 layer->onLayerDisplayed(releaseFence);
1942 }
1943 if (hwcId >= 0) {
1944 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001945 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001946 }
1947
Mathias Agopiana44b0412011-10-16 18:46:35 -07001948 mLastSwapBufferTime = systemTime() - now;
1949 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001950
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001951 // |mStateLock| not needed as we are on the main thread
1952 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001953 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1954 logFrameStats();
1955 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001956}
1957
Mathias Agopian87baae12012-07-31 12:38:26 -07001958void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001959{
Mathias Agopian841cde52012-03-01 15:44:37 -08001960 ATRACE_CALL();
1961
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001962 // here we keep a copy of the drawing state (that is the state that's
1963 // going to be overwritten by handleTransactionLocked()) outside of
1964 // mStateLock so that the side-effects of the State assignment
1965 // don't happen with mStateLock held (which can cause deadlocks).
1966 State drawingState(mDrawingState);
1967
Mathias Agopianca4d3602011-05-19 15:38:14 -07001968 Mutex::Autolock _l(mStateLock);
1969 const nsecs_t now = systemTime();
1970 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001971
Mathias Agopianca4d3602011-05-19 15:38:14 -07001972 // Here we're guaranteed that some transaction flags are set
1973 // so we can call handleTransactionLocked() unconditionally.
1974 // We call getTransactionFlags(), which will also clear the flags,
1975 // with mStateLock held to guarantee that mCurrentState won't change
1976 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001977
Mathias Agopiane57f2922012-08-09 16:29:12 -07001978 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001979 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001980
Mathias Agopianca4d3602011-05-19 15:38:14 -07001981 mLastTransactionTime = systemTime() - now;
1982 mDebugInTransaction = 0;
1983 invalidateHwcGeometry();
1984 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001985}
1986
Mathias Agopian87baae12012-07-31 12:38:26 -07001987void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001988{
Dan Stoza7dde5992015-05-22 09:51:44 -07001989 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001990 mCurrentState.traverseInZOrder([](Layer* layer) {
1991 layer->notifyAvailableFrames();
1992 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001993
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001994 /*
1995 * Traversal of the children
1996 * (perform the transaction for each of them if needed)
1997 */
1998
Mathias Agopian3559b072012-08-15 13:46:03 -07001999 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002000 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002001 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002002 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002003
2004 const uint32_t flags = layer->doTransaction(0);
2005 if (flags & Layer::eVisibleRegion)
2006 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002007 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002008 }
2009
2010 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002011 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002012 */
2013
Mathias Agopiane57f2922012-08-09 16:29:12 -07002014 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002015 // here we take advantage of Vector's copy-on-write semantics to
2016 // improve performance by skipping the transaction entirely when
2017 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002018 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2019 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002020 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002021 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002022 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002023 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002024
2025 // find the displays that were removed
2026 // (ie: in drawing state but not in current state)
2027 // also handle displays that changed
2028 // (ie: displays that are in both lists)
2029 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002030 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2031 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002032 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002033 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002034 // Call makeCurrent() on the primary display so we can
2035 // be sure that nothing associated with this display
2036 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002037 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002038 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002039 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002040 if (hw != NULL)
2041 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002042 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002043 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002044 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002045 } else {
2046 ALOGW("trying to remove the main display");
2047 }
2048 } else {
2049 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002050 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002051 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002052 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2053 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002054 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002055 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002056 // recreating the DisplayDevice, so we just remove it
2057 // from the drawing state, so that it get re-added
2058 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002059 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002060 if (hw != NULL)
2061 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002062 mDisplays.removeItem(display);
2063 mDrawingState.displays.removeItemsAt(i);
2064 dc--; i--;
2065 // at this point we must loop to the next item
2066 continue;
2067 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002068
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002069 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002070 if (disp != NULL) {
2071 if (state.layerStack != draw[i].layerStack) {
2072 disp->setLayerStack(state.layerStack);
2073 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002074 if ((state.orientation != draw[i].orientation)
2075 || (state.viewport != draw[i].viewport)
2076 || (state.frame != draw[i].frame))
2077 {
2078 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002079 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002080 }
Michael Lentine47e45402014-07-18 15:34:25 -07002081 if (state.width != draw[i].width || state.height != draw[i].height) {
2082 disp->setDisplaySize(state.width, state.height);
2083 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002084 }
2085 }
2086 }
2087
2088 // find displays that were added
2089 // (ie: in current state but not in drawing state)
2090 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002091 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002092 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002093
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002094 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002095 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002096 sp<IGraphicBufferProducer> bqProducer;
2097 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002098 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002099
Dan Stoza9e56aa02015-11-02 13:00:03 -08002100 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002101 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002102 // Virtual displays without a surface are dormant:
2103 // they have external state (layer stack, projection,
2104 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002105 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002106
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002107 // Allow VR composer to use virtual displays.
2108 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002109 int width = 0;
2110 int status = state.surface->query(
2111 NATIVE_WINDOW_WIDTH, &width);
2112 ALOGE_IF(status != NO_ERROR,
2113 "Unable to query width (%d)", status);
2114 int height = 0;
2115 status = state.surface->query(
2116 NATIVE_WINDOW_HEIGHT, &height);
2117 ALOGE_IF(status != NO_ERROR,
2118 "Unable to query height (%d)", status);
2119 int intFormat = 0;
2120 status = state.surface->query(
2121 NATIVE_WINDOW_FORMAT, &intFormat);
2122 ALOGE_IF(status != NO_ERROR,
2123 "Unable to query format (%d)", status);
2124 auto format = static_cast<android_pixel_format_t>(
2125 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002126
Dan Stoza8cf150a2016-08-02 10:27:31 -07002127 mHwc->allocateVirtualDisplay(width, height, &format,
2128 &hwcId);
2129 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002130
Dan Stoza5cf424b2016-05-20 14:02:39 -07002131 // TODO: Plumb requested format back up to consumer
2132
Dan Stoza9e56aa02015-11-02 13:00:03 -08002133 sp<VirtualDisplaySurface> vds =
2134 new VirtualDisplaySurface(*mHwc,
2135 hwcId, state.surface, bqProducer,
2136 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002137
2138 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002139 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002140 }
2141 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002142 ALOGE_IF(state.surface!=NULL,
2143 "adding a supported display, but rendering "
2144 "surface is provided (%p), ignoring it",
2145 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002146
2147 hwcId = state.type;
2148 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2149 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002150 }
2151
2152 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002153 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002154 sp<DisplayDevice> hw =
2155 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2156 dispSurface, producer,
2157 mRenderEngine->getEGLConfig(),
2158 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002159 hw->setLayerStack(state.layerStack);
2160 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002161 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002162 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002163 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002164 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002165 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002166 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002167 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002168 }
2169 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002170 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002171 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002172
Mathias Agopian84300952012-11-21 16:02:13 -08002173 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2174 // The transform hint might have changed for some layers
2175 // (either because a display has changed, or because a layer
2176 // as changed).
2177 //
2178 // Walk through all the layers in currentLayers,
2179 // and update their transform hint.
2180 //
2181 // If a layer is visible only on a single display, then that
2182 // display is used to calculate the hint, otherwise we use the
2183 // default display.
2184 //
2185 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2186 // the hint is set before we acquire a buffer from the surface texture.
2187 //
2188 // NOTE: layer transactions have taken place already, so we use their
2189 // drawing state. However, SurfaceFlinger's own transaction has not
2190 // happened yet, so we must use the current state layer list
2191 // (soon to become the drawing state list).
2192 //
2193 sp<const DisplayDevice> disp;
2194 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002195 bool first = true;
2196 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002197 // NOTE: we rely on the fact that layers are sorted by
2198 // layerStack first (so we don't have to traverse the list
2199 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002200 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002201 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002202 currentlayerStack = layerStack;
2203 // figure out if this layerstack is mirrored
2204 // (more than one display) if so, pick the default display,
2205 // if not, pick the only display it's on.
2206 disp.clear();
2207 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2208 sp<const DisplayDevice> hw(mDisplays[dpy]);
2209 if (hw->getLayerStack() == currentlayerStack) {
2210 if (disp == NULL) {
2211 disp = hw;
2212 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002213 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002214 break;
2215 }
2216 }
2217 }
2218 }
Chet Haase91d25932013-04-11 15:24:55 -07002219 if (disp == NULL) {
2220 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2221 // redraw after transform hint changes. See bug 8508397.
2222
2223 // could be null when this layer is using a layerStack
2224 // that is not visible on any display. Also can occur at
2225 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002226 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002227 }
Chet Haase91d25932013-04-11 15:24:55 -07002228 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002229
2230 first = false;
2231 });
Mathias Agopian84300952012-11-21 16:02:13 -08002232 }
2233
2234
Mathias Agopian3559b072012-08-15 13:46:03 -07002235 /*
2236 * Perform our own transaction if needed
2237 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002238
2239 if (mLayersAdded) {
2240 mLayersAdded = false;
2241 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002242 mVisibleRegionsDirty = true;
2243 }
2244
2245 // some layers might have been removed, so
2246 // we need to update the regions they're exposing.
2247 if (mLayersRemoved) {
2248 mLayersRemoved = false;
2249 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002250 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002251 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002252 // this layer is not visible anymore
2253 // TODO: we could traverse the tree from front to back and
2254 // compute the actual visible region
2255 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002256 Region visibleReg;
2257 visibleReg.set(layer->computeScreenBounds());
2258 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002259 }
Robert Carr2047fae2016-11-28 14:09:09 -08002260 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002261 }
2262
2263 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002264
2265 updateCursorAsync();
2266}
2267
2268void SurfaceFlinger::updateCursorAsync()
2269{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002270 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2271 auto& displayDevice = mDisplays[displayId];
2272 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002273 continue;
2274 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002275
2276 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2277 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002278 }
2279 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002280}
2281
2282void SurfaceFlinger::commitTransaction()
2283{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002284 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002285 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002286 for (const auto& l : mLayersPendingRemoval) {
2287 recordBufferingStats(l->getName().string(),
2288 l->getOccupancyHistory(true));
2289 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002290 }
2291 mLayersPendingRemoval.clear();
2292 }
2293
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002294 // If this transaction is part of a window animation then the next frame
2295 // we composite should be considered an animation as well.
2296 mAnimCompositionPending = mAnimTransactionPending;
2297
Mathias Agopian4fec8732012-06-29 14:12:52 -07002298 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002299 mDrawingState.traverseInZOrder([](Layer* layer) {
2300 layer->commitChildList();
2301 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002302 mTransactionPending = false;
2303 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002304 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002305}
2306
Robert Carr2047fae2016-11-28 14:09:09 -08002307void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002308 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309{
Mathias Agopian841cde52012-03-01 15:44:37 -08002310 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002311 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002312
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313 Region aboveOpaqueLayers;
2314 Region aboveCoveredLayers;
2315 Region dirty;
2316
Mathias Agopian87baae12012-07-31 12:38:26 -07002317 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002318
Robert Carr2047fae2016-11-28 14:09:09 -08002319 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002320 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002321 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002322
Jesse Hall01e29052013-02-19 16:13:35 -08002323 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002324 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002325 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002326
Mathias Agopianab028732010-03-16 16:41:46 -07002327 /*
2328 * opaqueRegion: area of a surface that is fully opaque.
2329 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002330 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002331
2332 /*
2333 * visibleRegion: area of a surface that is visible on screen
2334 * and not fully transparent. This is essentially the layer's
2335 * footprint minus the opaque regions above it.
2336 * Areas covered by a translucent surface are considered visible.
2337 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002338 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002339
2340 /*
2341 * coveredRegion: area of a surface that is covered by all
2342 * visible regions above it (which includes the translucent areas).
2343 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002345
Jesse Halla8026d22012-09-25 13:25:04 -07002346 /*
2347 * transparentRegion: area of a surface that is hinted to be completely
2348 * transparent. This is only used to tell when the layer has no visible
2349 * non-transparent regions and can be removed from the layer list. It
2350 * does not affect the visibleRegion of this layer or any layers
2351 * beneath it. The hint may not be correct if apps don't respect the
2352 * SurfaceView restrictions (which, sadly, some don't).
2353 */
2354 Region transparentRegion;
2355
Mathias Agopianab028732010-03-16 16:41:46 -07002356
2357 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002358 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002359 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002360 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002362 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002363 if (!visibleRegion.isEmpty()) {
2364 // Remove the transparent area from the visible region
2365 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002366 if (tr.preserveRects()) {
2367 // transform the transparent region
2368 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002369 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002370 // transformation too complex, can't do the
2371 // transparent region optimization.
2372 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002373 }
Mathias Agopianab028732010-03-16 16:41:46 -07002374 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002375
Mathias Agopianab028732010-03-16 16:41:46 -07002376 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002377 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002378 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002379 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2380 // the opaque region is the layer's footprint
2381 opaqueRegion = visibleRegion;
2382 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002383 }
2384 }
2385
Mathias Agopianab028732010-03-16 16:41:46 -07002386 // Clip the covered region to the visible region
2387 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2388
2389 // Update aboveCoveredLayers for next (lower) layer
2390 aboveCoveredLayers.orSelf(visibleRegion);
2391
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392 // subtract the opaque region covered by the layers above us
2393 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002394
2395 // compute this layer's dirty region
2396 if (layer->contentDirty) {
2397 // we need to invalidate the whole region
2398 dirty = visibleRegion;
2399 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002400 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002401 layer->contentDirty = false;
2402 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002403 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002404 * the exposed region consists of two components:
2405 * 1) what's VISIBLE now and was COVERED before
2406 * 2) what's EXPOSED now less what was EXPOSED before
2407 *
2408 * note that (1) is conservative, we start with the whole
2409 * visible region but only keep what used to be covered by
2410 * something -- which mean it may have been exposed.
2411 *
2412 * (2) handles areas that were not covered by anything but got
2413 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002414 */
Mathias Agopianab028732010-03-16 16:41:46 -07002415 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002416 const Region oldVisibleRegion = layer->visibleRegion;
2417 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002418 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2419 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002420 }
2421 dirty.subtractSelf(aboveOpaqueLayers);
2422
2423 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002424 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002425
Mathias Agopianab028732010-03-16 16:41:46 -07002426 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002427 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002428
Jesse Halla8026d22012-09-25 13:25:04 -07002429 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002430 layer->setVisibleRegion(visibleRegion);
2431 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002432 layer->setVisibleNonTransparentRegion(
2433 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002434 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002435
Mathias Agopian87baae12012-07-31 12:38:26 -07002436 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002437}
2438
Mathias Agopian87baae12012-07-31 12:38:26 -07002439void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2440 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002441 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002442 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2443 if (hw->getLayerStack() == layerStack) {
2444 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002445 }
2446 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002447}
2448
Dan Stoza6b9454d2014-11-07 16:00:59 -08002449bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002451 ALOGV("handlePageFlip");
2452
Brian Andersond6927fb2016-07-23 23:37:30 -07002453 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454
Mathias Agopian4fec8732012-06-29 14:12:52 -07002455 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002456 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002457 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002458
2459 // Store the set of layers that need updates. This set must not change as
2460 // buffers are being latched, as this could result in a deadlock.
2461 // Example: Two producers share the same command stream and:
2462 // 1.) Layer 0 is latched
2463 // 2.) Layer 0 gets a new frame
2464 // 2.) Layer 1 gets a new frame
2465 // 3.) Layer 1 is latched.
2466 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2467 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002468 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002469 if (layer->hasQueuedFrame()) {
2470 frameQueued = true;
2471 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002472 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002473 } else {
2474 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002475 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002476 } else {
2477 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002478 }
Robert Carr2047fae2016-11-28 14:09:09 -08002479 });
2480
Dan Stoza9e56aa02015-11-02 13:00:03 -08002481 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002482 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002483 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002484 invalidateLayerStack(layer->getLayerStack(), dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002485 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002486 newDataLatched = true;
2487 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002488 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002489
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002490 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002491
2492 // If we will need to wake up at some time in the future to deal with a
2493 // queued frame that shouldn't be displayed during this vsync period, wake
2494 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002495 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002496 signalLayerUpdate();
2497 }
2498
2499 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002500 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501}
2502
Mathias Agopianad456f92011-01-13 17:53:01 -08002503void SurfaceFlinger::invalidateHwcGeometry()
2504{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002505 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002506}
2507
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002508
Fabien Sanglard830b8472016-11-30 16:35:58 -08002509void SurfaceFlinger::doDisplayComposition(
2510 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002511 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512{
Dan Stoza71433162014-02-04 16:22:36 -08002513 // We only need to actually compose the display if:
2514 // 1) It is being handled by hardware composer, which may need this to
2515 // keep its virtual display state machine in sync, or
2516 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002517 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002518 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002519 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002520 return;
2521 }
2522
Dan Stoza9e56aa02015-11-02 13:00:03 -08002523 ALOGV("doDisplayComposition");
2524
Mathias Agopian87baae12012-07-31 12:38:26 -07002525 Region dirtyRegion(inDirtyRegion);
2526
Mathias Agopianb8a55602009-06-26 19:06:36 -07002527 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002528 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002529
Fabien Sanglard830b8472016-11-30 16:35:58 -08002530 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002531 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002532 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2533 // takes a rectangle, we must make sure to update that whole
2534 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002535 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002536 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002537 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002538 // We need to redraw the rectangle that will be updated
2539 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002540 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002541 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002542 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002543 } else {
2544 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002545 dirtyRegion.set(displayDevice->bounds());
2546 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547 }
2548 }
2549
Fabien Sanglard830b8472016-11-30 16:35:58 -08002550 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002552 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002553 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002554
2555 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002556 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557}
2558
Dan Stoza9e56aa02015-11-02 13:00:03 -08002559bool SurfaceFlinger::doComposeSurfaces(
2560 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002561{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002562 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002563
Dan Stoza9e56aa02015-11-02 13:00:03 -08002564 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002565
2566 mat4 oldColorMatrix;
2567 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2568 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2569 if (applyColorMatrix) {
2570 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2571 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2572 }
2573
Dan Stoza9e56aa02015-11-02 13:00:03 -08002574 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2575 if (hasClientComposition) {
2576 ALOGV("hasClientComposition");
2577
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002578#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002579 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002580 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002581#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002582 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002583 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002584 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002585 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002586
2587 // |mStateLock| not needed as we are on the main thread
2588 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002589 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2590 }
2591 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002592 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002593
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002594 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002595 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2596 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002597 // when using overlays, we assume a fully transparent framebuffer
2598 // NOTE: we could reduce how much we need to clear, for instance
2599 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002600 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002601 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002602 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002603 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002604 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002606
2607 // we remove the scissor part
2608 // we're left with the letterbox region
2609 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002610 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002611
2612 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002613 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002614
2615 // but limit it to the dirty region
2616 region.andSelf(dirty);
2617
Mathias Agopianb9494d52012-04-18 02:28:45 -07002618 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002619 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002620 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002621 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002622 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002623 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002624
Dan Stoza9e56aa02015-11-02 13:00:03 -08002625 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002626 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002627 // scissor on the main display. It should never be needed
2628 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002629 const Rect& bounds(displayDevice->getBounds());
2630 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002631 if (scissor != bounds) {
2632 // scissor doesn't match the screen's dimensions, so we
2633 // need to clear everything outside of it and enable
2634 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002635
Mathias Agopianf45c5102012-10-24 16:29:17 -07002636 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002637 const uint32_t height = displayDevice->getHeight();
2638 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002639 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002640 }
2641 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002642 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002643
Mathias Agopian85d751c2012-08-29 16:59:24 -07002644 /*
2645 * and then, render the layers targeted at the framebuffer
2646 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002647
Dan Stoza9e56aa02015-11-02 13:00:03 -08002648 ALOGV("Rendering client layers");
2649 const Transform& displayTransform = displayDevice->getTransform();
2650 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002651 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002652 bool firstLayer = true;
2653 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2654 const Region clip(dirty.intersect(
2655 displayTransform.transform(layer->visibleRegion)));
2656 ALOGV("Layer: %s", layer->getName().string());
2657 ALOGV(" Composition type: %s",
2658 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002659 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002660 switch (layer->getCompositionType(hwcId)) {
2661 case HWC2::Composition::Cursor:
2662 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002663 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002664 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002665 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002666 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2667 layer->isOpaque(state) && (state.alpha == 1.0f)
2668 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002669 // never clear the very first layer since we're
2670 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002671 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002672 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002673 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002674 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002675 case HWC2::Composition::Client: {
2676 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002677 break;
2678 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002679 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002680 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002681 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002682 } else {
2683 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002684 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002685 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002686 }
2687 } else {
2688 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002689 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002690 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002691 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002692 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002694 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002695 }
2696 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002697
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002698 if (applyColorMatrix) {
2699 getRenderEngine().setupColorTransform(oldColorMatrix);
2700 }
2701
Mathias Agopianf45c5102012-10-24 16:29:17 -07002702 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002703 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002704 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705}
2706
Fabien Sanglard830b8472016-11-30 16:35:58 -08002707void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2708 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002709 RenderEngine& engine(getRenderEngine());
2710 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711}
2712
Dan Stoza7d89d062015-04-30 13:29:25 -07002713status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002714 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002715 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002716 const sp<Layer>& lbc,
2717 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002718{
Dan Stoza7d89d062015-04-30 13:29:25 -07002719 // add this layer to the current state list
2720 {
2721 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002722 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002723 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2724 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002725 return NO_MEMORY;
2726 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002727 if (parent == nullptr) {
2728 mCurrentState.layersSortedByZ.add(lbc);
2729 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002730 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2731 ALOGE("addClientLayer called with a removed parent");
2732 return NAME_NOT_FOUND;
2733 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002734 parent->addChild(lbc);
2735 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002736
Dan Stoza7d89d062015-04-30 13:29:25 -07002737 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002738 mLayersAdded = true;
2739 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002740 }
2741
Mathias Agopian96f08192010-06-02 23:28:45 -07002742 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002743 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002744
Dan Stoza7d89d062015-04-30 13:29:25 -07002745 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002746}
2747
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002748status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002749 Mutex::Autolock _l(mStateLock);
2750
Robert Carr1f0a16a2016-10-24 16:27:39 -07002751 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002752 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002753 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002754 if (topLevelOnly) {
2755 return NO_ERROR;
2756 }
2757
Chia-I Wu98f1c102017-05-30 14:54:08 -07002758 sp<Layer> ancestor = p;
2759 while (ancestor->getParent() != nullptr) {
2760 ancestor = ancestor->getParent();
2761 }
2762 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2763 ALOGE("removeLayer called with a layer whose parent has been removed");
2764 return NAME_NOT_FOUND;
2765 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002766
2767 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002768 } else {
2769 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002770 }
2771
Robert Carr136e2f62017-02-08 17:54:29 -08002772 // As a matter of normal operation, the LayerCleaner will produce a second
2773 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2774 // so we will succeed in promoting it, but it's already been removed
2775 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2776 // otherwise something has gone wrong and we are leaking the layer.
2777 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002778 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2779 layer->getName().string(),
2780 (p != nullptr) ? p->getName().string() : "no-parent");
2781 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002782 } else if (index < 0) {
2783 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002784 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002785
2786 mLayersPendingRemoval.add(layer);
2787 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002788 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002789 setTransactionFlags(eTransactionNeeded);
2790 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791}
2792
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002793uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002794 return android_atomic_release_load(&mTransactionFlags);
2795}
2796
Mathias Agopian3f844832013-08-07 21:24:32 -07002797uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2799}
2800
Mathias Agopian3f844832013-08-07 21:24:32 -07002801uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2803 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002804 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002805 }
2806 return old;
2807}
2808
Mathias Agopian8b33f032012-07-24 20:43:54 -07002809void SurfaceFlinger::setTransactionState(
2810 const Vector<ComposerState>& state,
2811 const Vector<DisplayState>& displays,
2812 uint32_t flags)
2813{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002814 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002815 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002816 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002817
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002818 if (flags & eAnimation) {
2819 // For window updates that are part of an animation we must wait for
2820 // previous animation "frames" to be handled.
2821 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002822 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002823 if (CC_UNLIKELY(err != NO_ERROR)) {
2824 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002825 // caller after a few seconds.
2826 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2827 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002828 mAnimTransactionPending = false;
2829 break;
2830 }
2831 }
2832 }
2833
Mathias Agopiane57f2922012-08-09 16:29:12 -07002834 size_t count = displays.size();
2835 for (size_t i=0 ; i<count ; i++) {
2836 const DisplayState& s(displays[i]);
2837 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002838 }
2839
Mathias Agopiane57f2922012-08-09 16:29:12 -07002840 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002841 for (size_t i=0 ; i<count ; i++) {
2842 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002843 // Here we need to check that the interface we're given is indeed
2844 // one of our own. A malicious client could give us a NULL
2845 // IInterface, or one of its own or even one of our own but a
2846 // different type. All these situations would cause us to crash.
2847 //
2848 // NOTE: it would be better to use RTTI as we could directly check
2849 // that we have a Client*. however, RTTI is disabled in Android.
2850 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002851 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002852 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002853 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002854 sp<Client> client( static_cast<Client *>(s.client.get()) );
2855 transactionFlags |= setClientStateLocked(client, s.state);
2856 }
2857 }
2858 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002859 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002860
Robert Carr2a7dbb42016-05-24 11:41:28 -07002861 // If a synchronous transaction is explicitly requested without any changes,
2862 // force a transaction anyway. This can be used as a flush mechanism for
2863 // previous async transactions.
2864 if (transactionFlags == 0 && (flags & eSynchronous)) {
2865 transactionFlags = eTransactionNeeded;
2866 }
2867
Mathias Agopian386aa982011-11-07 21:58:03 -08002868 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002869 if (mInterceptor.isEnabled()) {
2870 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2871 }
Irvel468051e2016-06-13 16:44:44 -07002872
Mathias Agopian386aa982011-11-07 21:58:03 -08002873 // this triggers the transaction
2874 setTransactionFlags(transactionFlags);
2875
2876 // if this is a synchronous transaction, wait for it to take effect
2877 // before returning.
2878 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002879 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002880 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002881 if (flags & eAnimation) {
2882 mAnimTransactionPending = true;
2883 }
2884 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002885 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2886 if (CC_UNLIKELY(err != NO_ERROR)) {
2887 // just in case something goes wrong in SF, return to the
2888 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002889 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2890 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002891 break;
2892 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002893 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894 }
2895}
2896
Mathias Agopiane57f2922012-08-09 16:29:12 -07002897uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2898{
Jesse Hall9a143922012-10-04 16:29:19 -07002899 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2900 if (dpyIdx < 0)
2901 return 0;
2902
Mathias Agopiane57f2922012-08-09 16:29:12 -07002903 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002904 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002905 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002906 const uint32_t what = s.what;
2907 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002908 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002909 disp.surface = s.surface;
2910 flags |= eDisplayTransactionNeeded;
2911 }
2912 }
2913 if (what & DisplayState::eLayerStackChanged) {
2914 if (disp.layerStack != s.layerStack) {
2915 disp.layerStack = s.layerStack;
2916 flags |= eDisplayTransactionNeeded;
2917 }
2918 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002919 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002920 if (disp.orientation != s.orientation) {
2921 disp.orientation = s.orientation;
2922 flags |= eDisplayTransactionNeeded;
2923 }
2924 if (disp.frame != s.frame) {
2925 disp.frame = s.frame;
2926 flags |= eDisplayTransactionNeeded;
2927 }
2928 if (disp.viewport != s.viewport) {
2929 disp.viewport = s.viewport;
2930 flags |= eDisplayTransactionNeeded;
2931 }
2932 }
Michael Lentine47e45402014-07-18 15:34:25 -07002933 if (what & DisplayState::eDisplaySizeChanged) {
2934 if (disp.width != s.width) {
2935 disp.width = s.width;
2936 flags |= eDisplayTransactionNeeded;
2937 }
2938 if (disp.height != s.height) {
2939 disp.height = s.height;
2940 flags |= eDisplayTransactionNeeded;
2941 }
2942 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002943 }
2944 return flags;
2945}
2946
2947uint32_t SurfaceFlinger::setClientStateLocked(
2948 const sp<Client>& client,
2949 const layer_state_t& s)
2950{
2951 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002952 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002953 if (layer != 0) {
2954 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002955 bool geometryAppliesWithResize =
2956 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002957 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002958 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002959 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002960 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002961 }
2962 if (what & layer_state_t::eLayerChanged) {
2963 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002964 const auto& p = layer->getParent();
2965 if (p == nullptr) {
2966 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2967 if (layer->setLayer(s.z) && idx >= 0) {
2968 mCurrentState.layersSortedByZ.removeAt(idx);
2969 mCurrentState.layersSortedByZ.add(layer);
2970 // we need traversal (state changed)
2971 // AND transaction (list changed)
2972 flags |= eTransactionNeeded|eTraversalNeeded;
2973 }
2974 } else {
2975 if (p->setChildLayer(layer, s.z)) {
2976 flags |= eTransactionNeeded|eTraversalNeeded;
2977 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002978 }
2979 }
Robert Carrdb66e622017-04-10 16:55:57 -07002980 if (what & layer_state_t::eRelativeLayerChanged) {
2981 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2982 flags |= eTransactionNeeded|eTraversalNeeded;
2983 }
2984 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002985 if (what & layer_state_t::eSizeChanged) {
2986 if (layer->setSize(s.w, s.h)) {
2987 flags |= eTraversalNeeded;
2988 }
2989 }
2990 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002991 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002992 flags |= eTraversalNeeded;
2993 }
2994 if (what & layer_state_t::eMatrixChanged) {
2995 if (layer->setMatrix(s.matrix))
2996 flags |= eTraversalNeeded;
2997 }
2998 if (what & layer_state_t::eTransparentRegionChanged) {
2999 if (layer->setTransparentRegionHint(s.transparentRegion))
3000 flags |= eTraversalNeeded;
3001 }
Dan Stoza23116082015-06-18 14:58:39 -07003002 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003003 if (layer->setFlags(s.flags, s.mask))
3004 flags |= eTraversalNeeded;
3005 }
3006 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003007 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003008 flags |= eTraversalNeeded;
3009 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003010 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003011 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003012 flags |= eTraversalNeeded;
3013 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003014 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003015 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003016 // We only allow setting layer stacks for top level layers,
3017 // everything else inherits layer stack from its parent.
3018 if (layer->hasParent()) {
3019 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3020 layer->getName().string());
3021 } else if (idx < 0) {
3022 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3023 "that also does not appear in the top level layer list. Something"
3024 " has gone wrong.", layer->getName().string());
3025 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003026 mCurrentState.layersSortedByZ.removeAt(idx);
3027 mCurrentState.layersSortedByZ.add(layer);
3028 // we need traversal (state changed)
3029 // AND transaction (list changed)
3030 flags |= eTransactionNeeded|eTraversalNeeded;
3031 }
3032 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003033 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003034 if (s.barrierHandle != nullptr) {
3035 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3036 } else if (s.barrierGbp != nullptr) {
3037 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3038 if (authenticateSurfaceTextureLocked(gbp)) {
3039 const auto& otherLayer =
3040 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3041 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3042 } else {
3043 ALOGE("Attempt to defer transaction to to an"
3044 " unrecognized GraphicBufferProducer");
3045 }
3046 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003047 // We don't trigger a traversal here because if no other state is
3048 // changed, we don't want this to cause any more work
3049 }
Robert Carr1db73f62016-12-21 12:58:51 -08003050 if (what & layer_state_t::eReparentChildren) {
3051 if (layer->reparentChildren(s.reparentHandle)) {
3052 flags |= eTransactionNeeded|eTraversalNeeded;
3053 }
3054 }
Robert Carr9524cb32017-02-13 11:32:32 -08003055 if (what & layer_state_t::eDetachChildren) {
3056 layer->detachChildren();
3057 }
Robert Carrc3574f72016-03-24 12:19:32 -07003058 if (what & layer_state_t::eOverrideScalingModeChanged) {
3059 layer->setOverrideScalingMode(s.overrideScalingMode);
3060 // We don't trigger a traversal here because if no other state is
3061 // changed, we don't want this to cause any more work
3062 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003063 }
3064 return flags;
3065}
3066
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003067status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003068 const String8& name,
3069 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003070 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003071 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3072 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003074 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003075 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003076 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003077 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003078 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003079
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003080 status_t result = NO_ERROR;
3081
3082 sp<Layer> layer;
3083
Cody Northropbc755282017-03-31 12:00:08 -06003084 String8 uniqueName = getUniqueLayerName(name);
3085
Mathias Agopian3165cc22012-08-08 19:42:09 -07003086 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3087 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003088 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003089 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003090 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003092 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003093 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003094 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003095 handle, gbp, &layer);
3096 break;
3097 default:
3098 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099 break;
3100 }
3101
Dan Stoza7d89d062015-04-30 13:29:25 -07003102 if (result != NO_ERROR) {
3103 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003105
Albert Chaulk479c60c2017-01-27 14:21:34 -05003106 layer->setInfo(windowType, ownerUid);
3107
Robert Carr1f0a16a2016-10-24 16:27:39 -07003108 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003109 if (result != NO_ERROR) {
3110 return result;
3111 }
Irvelffc9efc2016-07-27 15:16:37 -07003112 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003113
3114 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003115 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003116}
3117
Cody Northropbc755282017-03-31 12:00:08 -06003118String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3119{
3120 bool matchFound = true;
3121 uint32_t dupeCounter = 0;
3122
3123 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3124 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3125
3126 // Loop over layers until we're sure there is no matching name
3127 while (matchFound) {
3128 matchFound = false;
3129 mDrawingState.traverseInZOrder([&](Layer* layer) {
3130 if (layer->getName() == uniqueName) {
3131 matchFound = true;
3132 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3133 }
3134 });
3135 }
3136
3137 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3138
3139 return uniqueName;
3140}
3141
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003142status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3143 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3144 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145{
3146 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003147 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148 case PIXEL_FORMAT_TRANSPARENT:
3149 case PIXEL_FORMAT_TRANSLUCENT:
3150 format = PIXEL_FORMAT_RGBA_8888;
3151 break;
3152 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003153 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 break;
3155 }
3156
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003157 *outLayer = new Layer(this, client, name, w, h, flags);
3158 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3159 if (err == NO_ERROR) {
3160 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003161 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003163
3164 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3165 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166}
3167
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003168status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3169 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3170 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003172 *outLayer = new LayerDim(this, client, name, w, h, flags);
3173 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003174 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003175 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003176}
3177
Mathias Agopianac9fa422013-02-11 16:40:36 -08003178status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179{
Robert Carr9524cb32017-02-13 11:32:32 -08003180 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003181 status_t err = NO_ERROR;
3182 sp<Layer> l(client->getLayerUser(handle));
3183 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003184 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003185 err = removeLayer(l);
3186 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3187 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003188 }
3189 return err;
3190}
3191
Mathias Agopian13127d82013-03-05 17:47:11 -08003192status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003193{
Mathias Agopian67106042013-03-14 19:18:13 -07003194 // called by ~LayerCleaner() when all references to the IBinder (handle)
3195 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003196 sp<Layer> l = layer.promote();
3197 if (l == nullptr) {
3198 // The layer has already been removed, carry on
3199 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003200 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003201 // If we have a parent, then we can continue to live as long as it does.
3202 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203}
3204
Mathias Agopianb60314a2012-04-10 22:09:54 -07003205// ---------------------------------------------------------------------------
3206
Andy McFadden13a082e2012-08-24 10:16:42 -07003207void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003208 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003209 Vector<ComposerState> state;
3210 Vector<DisplayState> displays;
3211 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003212 d.what = DisplayState::eDisplayProjectionChanged |
3213 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003214 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003215 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003216 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003217 d.frame.makeInvalid();
3218 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003219 d.width = 0;
3220 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003221 displays.add(d);
3222 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003223 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003224
Dan Stoza9e56aa02015-11-02 13:00:03 -08003225 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3226 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003227 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003228
Brian Andersond0010582017-03-07 13:20:31 -08003229 // Use phase of 0 since phase is not known.
3230 // Use latency of 0, which will snap to the ideal latency.
3231 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003232}
3233
3234void SurfaceFlinger::initializeDisplays() {
3235 class MessageScreenInitialized : public MessageBase {
3236 SurfaceFlinger* flinger;
3237 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003238 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003239 virtual bool handler() {
3240 flinger->onInitializeDisplays();
3241 return true;
3242 }
3243 };
3244 sp<MessageBase> msg = new MessageScreenInitialized(this);
3245 postMessageAsync(msg); // we may be called from main thread, use async message
3246}
3247
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003248void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3249 int mode) {
3250 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3251 this);
3252 int32_t type = hw->getDisplayType();
3253 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003254
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003255 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003256 return;
3257 }
3258
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003259 hw->setPowerMode(mode);
3260 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3261 ALOGW("Trying to set power mode for virtual display");
3262 return;
3263 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003264
Irvelffc9efc2016-07-27 15:16:37 -07003265 if (mInterceptor.isEnabled()) {
3266 Mutex::Autolock _l(mStateLock);
3267 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3268 if (idx < 0) {
3269 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3270 return;
3271 }
3272 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3273 }
3274
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003275 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003276 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003277 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003278 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3279 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003280 // FIXME: eventthread only knows about the main display right now
3281 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003282 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003283 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003284
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003285 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003286 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003287 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003288
3289 struct sched_param param = {0};
3290 param.sched_priority = 1;
3291 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3292 ALOGW("Couldn't set SCHED_FIFO on display on");
3293 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003294 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003295 // Turn off the display
3296 struct sched_param param = {0};
3297 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3298 ALOGW("Couldn't set SCHED_OTHER on display off");
3299 }
3300
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003301 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003302 disableHardwareVsync(true); // also cancels any in-progress resync
3303
Mathias Agopiancde87a32012-09-13 14:09:01 -07003304 // FIXME: eventthread only knows about the main display right now
3305 mEventThread->onScreenReleased();
3306 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003307
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003308 getHwComposer().setPowerMode(type, mode);
3309 mVisibleRegionsDirty = true;
3310 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003311 } else if (mode == HWC_POWER_MODE_DOZE ||
3312 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003313 // Update display while dozing
3314 getHwComposer().setPowerMode(type, mode);
3315 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3316 // FIXME: eventthread only knows about the main display right now
3317 mEventThread->onScreenAcquired();
3318 resyncToHardwareVsync(true);
3319 }
3320 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3321 // Leave display going to doze
3322 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3323 disableHardwareVsync(true); // also cancels any in-progress resync
3324 // FIXME: eventthread only knows about the main display right now
3325 mEventThread->onScreenReleased();
3326 }
3327 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003328 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003329 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003330 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003331 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003332}
3333
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003334void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3335 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003336 SurfaceFlinger& mFlinger;
3337 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003338 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003339 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003340 MessageSetPowerMode(SurfaceFlinger& flinger,
3341 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3342 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003343 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003344 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003345 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003346 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003347 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003348 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003349 ALOGW("Attempt to set power mode = %d for virtual display",
3350 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003351 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003352 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003353 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003354 return true;
3355 }
3356 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003357 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003358 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003359}
3360
3361// ---------------------------------------------------------------------------
3362
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003363status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3364{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003365 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003366
Mathias Agopianbd115332013-04-18 16:41:04 -07003367 IPCThreadState* ipc = IPCThreadState::self();
3368 const int pid = ipc->getCallingPid();
3369 const int uid = ipc->getCallingUid();
3370 if ((uid != AID_SHELL) &&
3371 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003372 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003373 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003374 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003375 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003376 // (this would indicate SF is stuck, but we want to be able to
3377 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003378 status_t err = mStateLock.timedLock(s2ns(1));
3379 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003380 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003381 result.appendFormat(
3382 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3383 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003384 }
3385
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003386 bool dumpAll = true;
3387 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003388 size_t numArgs = args.size();
3389 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003390 if ((index < numArgs) &&
3391 (args[index] == String16("--list"))) {
3392 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003393 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003394 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003395 }
3396
3397 if ((index < numArgs) &&
3398 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003399 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003400 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003401 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003402 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003403
3404 if ((index < numArgs) &&
3405 (args[index] == String16("--latency-clear"))) {
3406 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003407 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003408 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003409 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003410
3411 if ((index < numArgs) &&
3412 (args[index] == String16("--dispsync"))) {
3413 index++;
3414 mPrimaryDispSync.dump(result);
3415 dumpAll = false;
3416 }
Dan Stozab90cf072015-03-05 11:05:59 -08003417
3418 if ((index < numArgs) &&
3419 (args[index] == String16("--static-screen"))) {
3420 index++;
3421 dumpStaticScreenStats(result);
3422 dumpAll = false;
3423 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003424
3425 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003426 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003427 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003428 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003429 dumpAll = false;
3430 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003431
3432 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3433 index++;
3434 dumpWideColorInfo(result);
3435 dumpAll = false;
3436 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003437 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003438
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003439 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003440 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003441 }
3442
Mathias Agopian9795c422009-08-26 16:36:26 -07003443 if (locked) {
3444 mStateLock.unlock();
3445 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003446 }
3447 write(fd, result.string(), result.size());
3448 return NO_ERROR;
3449}
3450
Dan Stozac7014012014-02-14 15:03:43 -08003451void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3452 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003453{
Robert Carr2047fae2016-11-28 14:09:09 -08003454 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003455 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003456 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003457}
3458
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003459void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003460 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003461{
3462 String8 name;
3463 if (index < args.size()) {
3464 name = String8(args[index]);
3465 index++;
3466 }
3467
Dan Stoza9e56aa02015-11-02 13:00:03 -08003468 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3469 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003470 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003471
3472 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003473 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003474 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003475 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003476 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003477 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003478 }
Robert Carr2047fae2016-11-28 14:09:09 -08003479 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003480 }
3481}
3482
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003483void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003484 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003485{
3486 String8 name;
3487 if (index < args.size()) {
3488 name = String8(args[index]);
3489 index++;
3490 }
3491
Robert Carr2047fae2016-11-28 14:09:09 -08003492 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003493 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003494 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003495 }
Robert Carr2047fae2016-11-28 14:09:09 -08003496 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003497
Svetoslavd85084b2014-03-20 10:28:31 -07003498 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003499}
3500
Jamie Gennis6547ff42013-07-16 20:12:42 -07003501// This should only be called from the main thread. Otherwise it would need
3502// the lock and should use mCurrentState rather than mDrawingState.
3503void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003504 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003505 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003506 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003507
3508 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3509}
3510
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003511void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003512{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003513 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003514 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3515
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003516 if (isLayerTripleBufferingDisabled())
3517 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003518
3519 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003520 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003521 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003522 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003523 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3524 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003525 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003526}
3527
Dan Stozab90cf072015-03-05 11:05:59 -08003528void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3529{
3530 result.appendFormat("Static screen stats:\n");
3531 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3532 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3533 float percent = 100.0f *
3534 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3535 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3536 b + 1, bucketTimeSec, percent);
3537 }
3538 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3539 float percent = 100.0f *
3540 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3541 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3542 NUM_BUCKETS - 1, bucketTimeSec, percent);
3543}
3544
Dan Stozae77c7662016-05-13 11:37:28 -07003545void SurfaceFlinger::recordBufferingStats(const char* layerName,
3546 std::vector<OccupancyTracker::Segment>&& history) {
3547 Mutex::Autolock lock(mBufferingStatsMutex);
3548 auto& stats = mBufferingStats[layerName];
3549 for (const auto& segment : history) {
3550 if (!segment.usedThirdBuffer) {
3551 stats.twoBufferTime += segment.totalTime;
3552 }
3553 if (segment.occupancyAverage < 1.0f) {
3554 stats.doubleBufferedTime += segment.totalTime;
3555 } else if (segment.occupancyAverage < 2.0f) {
3556 stats.tripleBufferedTime += segment.totalTime;
3557 }
3558 ++stats.numSegments;
3559 stats.totalTime += segment.totalTime;
3560 }
3561}
3562
Brian Andersond6927fb2016-07-23 23:37:30 -07003563void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3564 result.appendFormat("Layer frame timestamps:\n");
3565
3566 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3567 const size_t count = currentLayers.size();
3568 for (size_t i=0 ; i<count ; i++) {
3569 currentLayers[i]->dumpFrameEvents(result);
3570 }
3571}
3572
Dan Stozae77c7662016-05-13 11:37:28 -07003573void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3574 result.append("Buffering stats:\n");
3575 result.append(" [Layer name] <Active time> <Two buffer> "
3576 "<Double buffered> <Triple buffered>\n");
3577 Mutex::Autolock lock(mBufferingStatsMutex);
3578 typedef std::tuple<std::string, float, float, float> BufferTuple;
3579 std::map<float, BufferTuple, std::greater<float>> sorted;
3580 for (const auto& statsPair : mBufferingStats) {
3581 const char* name = statsPair.first.c_str();
3582 const BufferingStats& stats = statsPair.second;
3583 if (stats.numSegments == 0) {
3584 continue;
3585 }
3586 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3587 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3588 stats.totalTime;
3589 float doubleBufferRatio = static_cast<float>(
3590 stats.doubleBufferedTime) / stats.totalTime;
3591 float tripleBufferRatio = static_cast<float>(
3592 stats.tripleBufferedTime) / stats.totalTime;
3593 sorted.insert({activeTime, {name, twoBufferRatio,
3594 doubleBufferRatio, tripleBufferRatio}});
3595 }
3596 for (const auto& sortedPair : sorted) {
3597 float activeTime = sortedPair.first;
3598 const BufferTuple& values = sortedPair.second;
3599 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3600 std::get<0>(values).c_str(), activeTime,
3601 std::get<1>(values), std::get<2>(values),
3602 std::get<3>(values));
3603 }
3604 result.append("\n");
3605}
3606
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003607void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3608 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3609
3610 // TODO: print out if wide-color mode is active or not
3611
3612 for (size_t d = 0; d < mDisplays.size(); d++) {
3613 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3614 int32_t hwcId = displayDevice->getHwcDisplayId();
3615 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3616 continue;
3617 }
3618
3619 result.appendFormat("Display %d color modes:\n", hwcId);
3620 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3621 for (auto&& mode : modes) {
3622 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3623 }
3624
3625 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3626 result.appendFormat(" Current color mode: %s (%d)\n",
3627 decodeColorMode(currentMode).c_str(), currentMode);
3628 }
3629 result.append("\n");
3630}
3631
Mathias Agopian74d211a2013-04-22 16:55:35 +02003632void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3633 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003634{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003635 bool colorize = false;
3636 if (index < args.size()
3637 && (args[index] == String16("--color"))) {
3638 colorize = true;
3639 index++;
3640 }
3641
3642 Colorizer colorizer(colorize);
3643
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003644 // figure out if we're stuck somewhere
3645 const nsecs_t now = systemTime();
3646 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3647 const nsecs_t inTransaction(mDebugInTransaction);
3648 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3649 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3650
3651 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003652 * Dump library configuration.
3653 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003654
3655 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003656 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003657 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003658 appendSfConfigString(result);
3659 appendUiConfigString(result);
3660 appendGuiConfigString(result);
3661 result.append("\n");
3662
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003663 result.append("\nWide-Color information:\n");
3664 dumpWideColorInfo(result);
3665
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003666 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003667 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003668 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003669 result.append(SyncFeatures::getInstance().toString());
3670 result.append("\n");
3671
Dan Stoza9e56aa02015-11-02 13:00:03 -08003672 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3673
Andy McFadden41d67d72014-04-25 16:58:34 -07003674 colorizer.bold(result);
3675 result.append("DispSync configuration: ");
3676 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003677 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003678 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003679 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003680 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003681 result.append("\n");
3682
Dan Stozab90cf072015-03-05 11:05:59 -08003683 // Dump static screen stats
3684 result.append("\n");
3685 dumpStaticScreenStats(result);
3686 result.append("\n");
3687
Dan Stozae77c7662016-05-13 11:37:28 -07003688 dumpBufferingStats(result);
3689
Andy McFadden4803b742012-09-24 19:07:20 -07003690 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003691 * Dump the visible layer list
3692 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003693 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003694 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003695 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003696 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003697 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003698 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003699
3700 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003701 * Dump Display state
3702 */
3703
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003704 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003705 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003706 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003707 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3708 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003709 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003710 }
3711
3712 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003713 * Dump SurfaceFlinger global state
3714 */
3715
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003716 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003717 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003718 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003719
Mathias Agopian888c8222012-08-04 21:10:38 -07003720 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003721 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003722
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003723 colorizer.bold(result);
3724 result.appendFormat("EGL implementation : %s\n",
3725 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3726 colorizer.reset(result);
3727 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003728 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003729
Mathias Agopian875d8e12013-06-07 15:35:48 -07003730 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003731
Mathias Agopian42977342012-08-05 00:40:46 -07003732 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003733 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3734 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003735 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003736 " last eglSwapBuffers() time: %f us\n"
3737 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003738 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003739 " refresh-rate : %f fps\n"
3740 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003741 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003742 " gpu_to_cpu_unsupported : %d\n"
3743 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003744 mLastSwapBufferTime/1000.0,
3745 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003746 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003747 1e9 / activeConfig->getVsyncPeriod(),
3748 activeConfig->getDpiX(),
3749 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003750 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003751
Mathias Agopian74d211a2013-04-22 16:55:35 +02003752 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003753 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003754
Mathias Agopian74d211a2013-04-22 16:55:35 +02003755 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003756 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003757
3758 /*
3759 * VSYNC state
3760 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003761 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003762 result.append("\n");
3763
3764 /*
3765 * HWC layer minidump
3766 */
3767 for (size_t d = 0; d < mDisplays.size(); d++) {
3768 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3769 int32_t hwcId = displayDevice->getHwcDisplayId();
3770 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3771 continue;
3772 }
3773
3774 result.appendFormat("Display %d HWC layers:\n", hwcId);
3775 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003776 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003777 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003778 });
Dan Stozae22aec72016-08-01 13:20:59 -07003779 result.append("\n");
3780 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003781
3782 /*
3783 * Dump HWComposer state
3784 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003785 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003786 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003787 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003788 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003789 result.appendFormat(" h/w composer %s\n",
3790 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003791 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003792
3793 /*
3794 * Dump gralloc state
3795 */
3796 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3797 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003798
3799 /*
3800 * Dump VrFlinger state if in use.
3801 */
3802 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3803 result.append("VrFlinger state:\n");
3804 result.append(mVrFlinger->Dump().c_str());
3805 result.append("\n");
3806 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003807}
3808
Mathias Agopian13127d82013-03-05 17:47:11 -08003809const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003810SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003811 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003812 wp<IBinder> dpy;
3813 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3814 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3815 dpy = mDisplays.keyAt(i);
3816 break;
3817 }
3818 }
3819 if (dpy == NULL) {
3820 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3821 // Just use the primary display so we have something to return
3822 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3823 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003824 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003825}
3826
Keun young Park63f165f2012-08-31 10:53:36 -07003827bool SurfaceFlinger::startDdmConnection()
3828{
3829 void* libddmconnection_dso =
3830 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3831 if (!libddmconnection_dso) {
3832 return false;
3833 }
3834 void (*DdmConnection_start)(const char* name);
3835 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003836 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003837 if (!DdmConnection_start) {
3838 dlclose(libddmconnection_dso);
3839 return false;
3840 }
3841 (*DdmConnection_start)(getServiceName());
3842 return true;
3843}
3844
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003845status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003846 switch (code) {
3847 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003848 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003849 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003850 case CLEAR_ANIMATION_FRAME_STATS:
3851 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003852 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003853 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003854 {
3855 // codes that require permission check
3856 IPCThreadState* ipc = IPCThreadState::self();
3857 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003858 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003859 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003860 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003861 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003862 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003863 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003864 break;
3865 }
Robert Carr1db73f62016-12-21 12:58:51 -08003866 /*
3867 * Calling setTransactionState is safe, because you need to have been
3868 * granted a reference to Client* and Handle* to do anything with it.
3869 *
3870 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3871 */
3872 case SET_TRANSACTION_STATE:
3873 case CREATE_SCOPED_CONNECTION:
3874 {
3875 return OK;
3876 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003877 case CAPTURE_SCREEN:
3878 {
3879 // codes that require permission check
3880 IPCThreadState* ipc = IPCThreadState::self();
3881 const int pid = ipc->getCallingPid();
3882 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003883 if ((uid != AID_GRAPHICS) &&
3884 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003885 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003886 return PERMISSION_DENIED;
3887 }
3888 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003889 }
3890 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003891 return OK;
3892}
3893
3894status_t SurfaceFlinger::onTransact(
3895 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3896{
3897 status_t credentialCheck = CheckTransactCodeCredentials(code);
3898 if (credentialCheck != OK) {
3899 return credentialCheck;
3900 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003901
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003902 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3903 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003904 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003905 IPCThreadState* ipc = IPCThreadState::self();
3906 const int uid = ipc->getCallingUid();
3907 if (CC_UNLIKELY(uid != AID_SYSTEM
3908 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003909 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003910 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003911 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003912 return PERMISSION_DENIED;
3913 }
3914 int n;
3915 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003916 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003917 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918 return NO_ERROR;
3919 case 1002: // SHOW_UPDATES
3920 n = data.readInt32();
3921 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003922 invalidateHwcGeometry();
3923 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003924 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003925 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003926 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003927 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003929 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003930 setTransactionFlags(
3931 eTransactionNeeded|
3932 eDisplayTransactionNeeded|
3933 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003934 return NO_ERROR;
3935 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003936 case 1006:{ // send empty update
3937 signalRefresh();
3938 return NO_ERROR;
3939 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003940 case 1008: // toggle use of hw composer
3941 n = data.readInt32();
3942 mDebugDisableHWC = n ? 1 : 0;
3943 invalidateHwcGeometry();
3944 repaintEverything();
3945 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003946 case 1009: // toggle use of transform hint
3947 n = data.readInt32();
3948 mDebugDisableTransformHint = n ? 1 : 0;
3949 invalidateHwcGeometry();
3950 repaintEverything();
3951 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003952 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003953 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003954 reply->writeInt32(0);
3955 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003956 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003957 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003958 return NO_ERROR;
3959 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003960 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003961 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003962 return NO_ERROR;
3963 }
3964 case 1014: {
3965 // daltonize
3966 n = data.readInt32();
3967 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003968 case 1:
3969 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3970 break;
3971 case 2:
3972 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3973 break;
3974 case 3:
3975 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3976 break;
3977 default:
3978 mDaltonizer.setType(ColorBlindnessType::None);
3979 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003980 }
3981 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003982 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003983 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003984 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003985 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003986 invalidateHwcGeometry();
3987 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003988 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003989 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003990 case 1015: {
3991 // apply a color matrix
3992 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003993 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07003994 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07003995 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003996 for (size_t j = 0; j < 4; j++) {
3997 mColorMatrix[i][j] = data.readFloat();
3998 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003999 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004000 } else {
4001 mColorMatrix = mat4();
4002 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004003
4004 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4005 // the division by w in the fragment shader
4006 float4 lastRow(transpose(mColorMatrix)[3]);
4007 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4008 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4009 }
4010
Alan Viverette9c5a3332013-09-12 20:04:35 -07004011 invalidateHwcGeometry();
4012 repaintEverything();
4013 return NO_ERROR;
4014 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004015 // This is an experimental interface
4016 // Needs to be shifted to proper binder interface when we productize
4017 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004018 n = data.readInt32();
4019 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004020 return NO_ERROR;
4021 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004022 case 1017: {
4023 n = data.readInt32();
4024 mForceFullDamage = static_cast<bool>(n);
4025 return NO_ERROR;
4026 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004027 case 1018: { // Modify Choreographer's phase offset
4028 n = data.readInt32();
4029 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4030 return NO_ERROR;
4031 }
4032 case 1019: { // Modify SurfaceFlinger's phase offset
4033 n = data.readInt32();
4034 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4035 return NO_ERROR;
4036 }
Irvel468051e2016-06-13 16:44:44 -07004037 case 1020: { // Layer updates interceptor
4038 n = data.readInt32();
4039 if (n) {
4040 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004041 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004042 }
4043 else{
4044 ALOGV("Interceptor disabled");
4045 mInterceptor.disable();
4046 }
4047 return NO_ERROR;
4048 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004049 case 1021: { // Disable HWC virtual displays
4050 n = data.readInt32();
4051 mUseHwcVirtualDisplays = !n;
4052 return NO_ERROR;
4053 }
Romain Guy0147a172017-06-01 13:53:56 -07004054 case 1022: { // Set saturation boost
4055 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4056
4057 invalidateHwcGeometry();
4058 repaintEverything();
4059 return NO_ERROR;
4060 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004061 }
4062 }
4063 return err;
4064}
4065
Mathias Agopian53331da2011-08-22 21:44:41 -07004066void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004067 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004068 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004069}
4070
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004071// Checks that the requested width and height are valid and updates them to the display dimensions
4072// if they are set to 0
4073static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4074 Transform::orientation_flags rotation,
4075 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4076 // get screen geometry
4077 uint32_t displayWidth = displayDevice->getWidth();
4078 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004079
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004080 if (rotation & Transform::ROT_90) {
4081 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004082 }
4083
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004084 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4085 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4086 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4087 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004088 }
4089
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004090 if (*requestedWidth == 0) {
4091 *requestedWidth = displayWidth;
4092 }
4093 if (*requestedHeight == 0) {
4094 *requestedHeight = displayHeight;
4095 }
4096
4097 return NO_ERROR;
4098}
4099
4100// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4101class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004102public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004103 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4104 ~WindowDisconnector() {
4105 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004106 }
4107
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004108private:
4109 ANativeWindow* mWindow;
4110 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004111};
4112
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004113static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4114 uint32_t requestedHeight, bool hasWideColorDisplay,
4115 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4116 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4117 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4118
4119 int err = 0;
4120 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4121 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4122 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4123 err |= native_window_set_usage(window, usage);
4124
4125 if (hasWideColorDisplay) {
4126 err |= native_window_set_buffers_data_space(window,
4127 renderEngineUsesWideColor
4128 ? HAL_DATASPACE_DISPLAY_P3
4129 : HAL_DATASPACE_V0_SRGB);
4130 }
4131
4132 if (err != NO_ERROR) {
4133 return BAD_VALUE;
4134 }
4135
4136 /* TODO: Once we have the sync framework everywhere this can use
4137 * server-side waits on the fence that dequeueBuffer returns.
4138 */
4139 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4140 if (err != NO_ERROR) {
4141 return err;
4142 }
4143
4144 return NO_ERROR;
4145}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004146
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004147status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4148 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004149 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004150 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004151 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004152 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004153
4154 if (CC_UNLIKELY(display == 0))
4155 return BAD_VALUE;
4156
4157 if (CC_UNLIKELY(producer == 0))
4158 return BAD_VALUE;
4159
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004160 // if we have secure windows on this display, never allow the screen capture
4161 // unless the producer interface is local (i.e.: we can take a screenshot for
4162 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004163 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004164
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004165 // Convert to surfaceflinger's internal rotation type.
4166 Transform::orientation_flags rotationFlags;
4167 switch (rotation) {
4168 case ISurfaceComposer::eRotateNone:
4169 rotationFlags = Transform::ROT_0;
4170 break;
4171 case ISurfaceComposer::eRotate90:
4172 rotationFlags = Transform::ROT_90;
4173 break;
4174 case ISurfaceComposer::eRotate180:
4175 rotationFlags = Transform::ROT_180;
4176 break;
4177 case ISurfaceComposer::eRotate270:
4178 rotationFlags = Transform::ROT_270;
4179 break;
4180 default:
4181 rotationFlags = Transform::ROT_0;
4182 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4183 break;
4184 }
4185
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004186 { // Autolock scope
4187 Mutex::Autolock lock(mStateLock);
4188 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4189 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004190 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004191
4192 // create a surface (because we're a producer, and we need to
4193 // dequeue/queue a buffer)
4194 sp<Surface> surface = new Surface(producer, false);
4195
4196 // Put the screenshot Surface into async mode so that
4197 // Layer::headFenceHasSignaled will always return true and we'll latch the
4198 // first buffer regardless of whether or not its acquire fence has
4199 // signaled. This is needed to avoid a race condition in the rotation
4200 // animation. See b/30209608
4201 surface->setAsyncMode(true);
4202
4203 ANativeWindow* window = surface.get();
4204
4205 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4206 if (result != NO_ERROR) {
4207 return result;
4208 }
4209 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4210
4211 ANativeWindowBuffer* buffer = nullptr;
4212 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4213 getRenderEngine().usesWideColor(), &buffer);
4214 if (result != NO_ERROR) {
4215 return result;
4216 }
4217
4218 // This mutex protects syncFd and captureResult for communication of the return values from the
4219 // main thread back to this Binder thread
4220 std::mutex captureMutex;
4221 std::condition_variable captureCondition;
4222 std::unique_lock<std::mutex> captureLock(captureMutex);
4223 int syncFd = -1;
4224 std::optional<status_t> captureResult;
4225
4226 sp<LambdaMessage> message = new LambdaMessage([&]() {
4227 // If there is a refresh pending, bug out early and tell the binder thread to try again
4228 // after the refresh.
4229 if (mRefreshPending) {
4230 ATRACE_NAME("Skipping screenshot for now");
4231 std::unique_lock<std::mutex> captureLock(captureMutex);
4232 captureResult = std::make_optional<status_t>(EAGAIN);
4233 captureCondition.notify_one();
4234 return;
4235 }
4236
4237 status_t result = NO_ERROR;
4238 int fd = -1;
4239 {
4240 Mutex::Autolock _l(mStateLock);
4241 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4242 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4243 minLayerZ, maxLayerZ, useIdentityTransform,
4244 rotationFlags, isLocalScreenshot, &fd);
4245 }
4246
4247 {
4248 std::unique_lock<std::mutex> captureLock(captureMutex);
4249 syncFd = fd;
4250 captureResult = std::make_optional<status_t>(result);
4251 captureCondition.notify_one();
4252 }
4253 });
4254
4255 result = postMessageAsync(message);
4256 if (result == NO_ERROR) {
4257 captureCondition.wait(captureLock, [&]() { return captureResult; });
4258 while (*captureResult == EAGAIN) {
4259 captureResult.reset();
4260 result = postMessageAsync(message);
4261 if (result != NO_ERROR) {
4262 return result;
4263 }
4264 captureCondition.wait(captureLock, [&]() { return captureResult; });
4265 }
4266 result = *captureResult;
4267 }
4268
4269 if (result == NO_ERROR) {
4270 // queueBuffer takes ownership of syncFd
4271 result = window->queueBuffer(window, buffer, syncFd);
4272 }
4273
4274 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004275}
4276
Mathias Agopian180f10d2013-04-10 22:55:41 -07004277
4278void SurfaceFlinger::renderScreenImplLocked(
4279 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004280 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004281 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004282 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004283{
4284 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004285 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004286
4287 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004288 const int32_t hw_w = hw->getWidth();
4289 const int32_t hw_h = hw->getHeight();
4290 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004291 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004292
Dan Stozac1879002014-05-22 15:59:05 -07004293 // if a default or invalid sourceCrop is passed in, set reasonable values
4294 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4295 !sourceCrop.isValid()) {
4296 sourceCrop.setLeftTop(Point(0, 0));
4297 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4298 }
4299
4300 // ensure that sourceCrop is inside screen
4301 if (sourceCrop.left < 0) {
4302 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4303 }
Dan Stozabe31f442014-06-11 11:20:54 -07004304 if (sourceCrop.right > hw_w) {
4305 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004306 }
4307 if (sourceCrop.top < 0) {
4308 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4309 }
Dan Stozabe31f442014-06-11 11:20:54 -07004310 if (sourceCrop.bottom > hw_h) {
4311 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004312 }
4313
Romain Guy88d37dd2017-05-26 17:57:05 -07004314#ifdef USE_HWC2
4315 engine.setWideColor(hw->getWideColorSupport());
4316 engine.setColorMode(hw->getActiveColorMode());
4317#endif
4318
Mathias Agopian180f10d2013-04-10 22:55:41 -07004319 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004320 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004321
4322 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004323 engine.setViewportAndProjection(
4324 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004325 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004326
4327 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004328 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004329
Robert Carr1f0a16a2016-10-24 16:27:39 -07004330 // We loop through the first level of layers without traversing,
4331 // as we need to interpret min/max layer Z in the top level Z space.
4332 for (const auto& layer : mDrawingState.layersSortedByZ) {
4333 if (layer->getLayerStack() != hw->getLayerStack()) {
4334 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004335 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004336 const Layer::State& state(layer->getDrawingState());
4337 if (state.z < minLayerZ || state.z > maxLayerZ) {
4338 continue;
4339 }
Dan Stoza412903f2017-04-27 13:42:17 -07004340 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004341 if (!layer->isVisible()) {
4342 return;
4343 }
4344 if (filtering) layer->setFiltering(true);
4345 layer->draw(hw, useIdentityTransform);
4346 if (filtering) layer->setFiltering(false);
4347 });
4348 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004349
Mathias Agopian931bda12013-08-28 18:11:46 -07004350 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004351}
4352
Dan Stozaabcda352017-06-01 14:37:39 -07004353// A simple RAII class that holds an EGLImage and destroys it either:
4354// a) When the destroy() method is called
4355// b) When the object goes out of scope
4356class ImageHolder {
4357public:
4358 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4359 ~ImageHolder() { destroy(); }
4360
4361 void destroy() {
4362 if (mImage != EGL_NO_IMAGE_KHR) {
4363 eglDestroyImageKHR(mDisplay, mImage);
4364 mImage = EGL_NO_IMAGE_KHR;
4365 }
4366 }
4367
4368private:
4369 const EGLDisplay mDisplay;
4370 EGLImageKHR mImage;
4371};
4372
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004373status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4374 ANativeWindowBuffer* buffer, Rect sourceCrop,
4375 uint32_t reqWidth, uint32_t reqHeight,
4376 int32_t minLayerZ, int32_t maxLayerZ,
4377 bool useIdentityTransform,
4378 Transform::orientation_flags rotation,
4379 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004380 ATRACE_CALL();
4381
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004382 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004383 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004384 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004385 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4386 (state.z < minLayerZ || state.z > maxLayerZ)) {
4387 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004388 }
Dan Stoza412903f2017-04-27 13:42:17 -07004389 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004390 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4391 layer->isSecure());
4392 });
4393 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004394
4395 if (!isLocalScreenshot && secureLayerIsVisible) {
4396 ALOGW("FB is protected: PERMISSION_DENIED");
4397 return PERMISSION_DENIED;
4398 }
4399
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004400 int syncFd = -1;
4401 // create an EGLImage from the buffer so we can later
4402 // turn it into a texture
4403 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4404 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4405 if (image == EGL_NO_IMAGE_KHR) {
4406 return BAD_VALUE;
4407 }
4408
Dan Stozaabcda352017-06-01 14:37:39 -07004409 // This will automatically destroy the image if we return before calling its destroy method
4410 ImageHolder imageHolder(mEGLDisplay, image);
4411
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004412 // this binds the given EGLImage as a framebuffer for the
4413 // duration of this scope.
4414 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004415 if (imageBond.getStatus() != NO_ERROR) {
4416 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004417 return INVALID_OPERATION;
4418 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004419
Dan Stozaabcda352017-06-01 14:37:39 -07004420 // this will in fact render into our dequeued buffer
4421 // via an FBO, which means we didn't have to create
4422 // an EGLSurface and therefore we're not
4423 // dependent on the context's EGLConfig.
4424 renderScreenImplLocked(
4425 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4426 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004427
Dan Stozaabcda352017-06-01 14:37:39 -07004428 // Attempt to create a sync khr object that can produce a sync point. If that
4429 // isn't available, create a non-dupable sync object in the fallback path and
4430 // wait on it directly.
4431 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4432 if (!DEBUG_SCREENSHOTS) {
4433 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4434 // native fence fd will not be populated until flush() is done.
4435 getRenderEngine().flush();
4436 }
4437
4438 if (sync != EGL_NO_SYNC_KHR) {
4439 // get the sync fd
4440 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4441 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4442 ALOGW("captureScreen: failed to dup sync khr object");
4443 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004444 }
Dan Stozaabcda352017-06-01 14:37:39 -07004445 eglDestroySyncKHR(mEGLDisplay, sync);
4446 } else {
4447 // fallback path
4448 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004449 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004450 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4451 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4452 EGLint eglErr = eglGetError();
4453 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4454 ALOGW("captureScreen: fence wait timed out");
4455 } else {
4456 ALOGW_IF(eglErr != EGL_SUCCESS,
4457 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004458 }
4459 eglDestroySyncKHR(mEGLDisplay, sync);
4460 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004461 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004462 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004463 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004464 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004465
4466 if (DEBUG_SCREENSHOTS) {
4467 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4468 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4469 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4470 hw, minLayerZ, maxLayerZ);
4471 delete [] pixels;
4472 }
4473
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004474 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004475 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004476
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004477 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004478}
4479
Mathias Agopiand5556842013-09-19 17:08:37 -07004480void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004481 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004482 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004483 for (size_t y=0 ; y<h ; y++) {
4484 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4485 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004486 if (p[x] != 0xFF000000) return;
4487 }
4488 }
4489 ALOGE("*** we just took a black screenshot ***\n"
4490 "requested minz=%d, maxz=%d, layerStack=%d",
4491 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004492
Robert Carr2047fae2016-11-28 14:09:09 -08004493 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004494 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004495 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004496 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4497 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004498 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004499 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4500 layer->isVisible() ? '+' : '-',
4501 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004502 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004503 i++;
4504 });
4505 }
4506 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004507 }
4508}
4509
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004510// ---------------------------------------------------------------------------
4511
Dan Stoza412903f2017-04-27 13:42:17 -07004512void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4513 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004514}
4515
Dan Stoza412903f2017-04-27 13:42:17 -07004516void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4517 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004518}
4519
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004520}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004521
4522
4523#if defined(__gl_h_)
4524#error "don't include gl/gl.h in this file"
4525#endif
4526
4527#if defined(__gl2_h_)
4528#error "don't include gl2/gl2.h in this file"
4529#endif