blob: d30f2e24d70a3b5dd5793d455d547bcf512111a3 [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 Agopian3330b202009-10-05 17:07:12 -0700357 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700358
359 // wait patiently for the window manager death
360 const String16 name("window");
361 sp<IBinder> window(defaultServiceManager()->getService(name));
362 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700363 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700364 }
365
Steven Thomas050b2c82017-03-06 11:45:16 -0800366 if (mVrFlinger) {
367 mVrFlinger->OnBootFinished();
368 }
369
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700370 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700371 // formerly we would just kill the process, but we now ask it to exit so it
372 // can choose where to stop the animation.
373 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700374
375 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
376 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
377 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700378
379 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
380 readPersistentProperties();
381 });
382 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800383}
384
Mathias Agopian3f844832013-08-07 21:24:32 -0700385void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700386 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700387 RenderEngine& engine;
388 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700389 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700390 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
391 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700392 }
393 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700394 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700395 return true;
396 }
397 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700398 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700399}
400
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700401class DispSyncSource : public VSyncSource, private DispSync::Callback {
402public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700403 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000404 const char* name) :
405 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700406 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700407 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000408 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
409 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700410 mDispSync(dispSync),
411 mCallbackMutex(),
412 mCallback(),
413 mVsyncMutex(),
414 mPhaseOffset(phaseOffset),
415 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700416
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700417 virtual ~DispSyncSource() {}
418
419 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700420 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000422 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700423 static_cast<DispSync::Callback*>(this));
424 if (err != NO_ERROR) {
425 ALOGE("error registering vsync callback: %s (%d)",
426 strerror(-err), err);
427 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700428 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429 } else {
430 status_t err = mDispSync->removeEventListener(
431 static_cast<DispSync::Callback*>(this));
432 if (err != NO_ERROR) {
433 ALOGE("error unregistering vsync callback: %s (%d)",
434 strerror(-err), err);
435 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700436 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700437 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700438 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700439 }
440
441 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700442 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443 mCallback = callback;
444 }
445
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700446 virtual void setPhaseOffset(nsecs_t phaseOffset) {
447 Mutex::Autolock lock(mVsyncMutex);
448
449 // Normalize phaseOffset to [0, period)
450 auto period = mDispSync->getPeriod();
451 phaseOffset %= period;
452 if (phaseOffset < 0) {
453 // If we're here, then phaseOffset is in (-period, 0). After this
454 // operation, it will be in (0, period)
455 phaseOffset += period;
456 }
457 mPhaseOffset = phaseOffset;
458
459 // If we're not enabled, we don't need to mess with the listeners
460 if (!mEnabled) {
461 return;
462 }
463
464 // Remove the listener with the old offset
465 status_t err = mDispSync->removeEventListener(
466 static_cast<DispSync::Callback*>(this));
467 if (err != NO_ERROR) {
468 ALOGE("error unregistering vsync callback: %s (%d)",
469 strerror(-err), err);
470 }
471
472 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000473 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700474 static_cast<DispSync::Callback*>(this));
475 if (err != NO_ERROR) {
476 ALOGE("error registering vsync callback: %s (%d)",
477 strerror(-err), err);
478 }
479 }
480
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481private:
482 virtual void onDispSyncEvent(nsecs_t when) {
483 sp<VSyncSource::Callback> callback;
484 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700485 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700486 callback = mCallback;
487
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700488 if (mTraceVsync) {
489 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700490 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700491 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700492 }
493
494 if (callback != NULL) {
495 callback->onVSyncEvent(when);
496 }
497 }
498
Tim Murray4a4e4a22016-04-19 16:29:23 +0000499 const char* const mName;
500
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501 int mValue;
502
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700503 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700504 const String8 mVsyncOnLabel;
505 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700506
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700508
509 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511
512 Mutex mVsyncMutex; // Protects the following
513 nsecs_t mPhaseOffset;
514 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700515};
516
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700517class InjectVSyncSource : public VSyncSource {
518public:
519 InjectVSyncSource() {}
520
521 virtual ~InjectVSyncSource() {}
522
523 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
524 std::lock_guard<std::mutex> lock(mCallbackMutex);
525 mCallback = callback;
526 }
527
528 virtual void onInjectSyncEvent(nsecs_t when) {
529 std::lock_guard<std::mutex> lock(mCallbackMutex);
530 mCallback->onVSyncEvent(when);
531 }
532
533 virtual void setVSyncEnabled(bool) {}
534 virtual void setPhaseOffset(nsecs_t) {}
535
536private:
537 std::mutex mCallbackMutex; // Protects the following
538 sp<VSyncSource::Callback> mCallback;
539};
540
Wei Wangf9b05ee2017-07-19 20:59:39 -0700541// Do not call property_set on main thread which will be blocked by init
542// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700543void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700544 ALOGI( "SurfaceFlinger's main thread ready to run. "
545 "Initializing graphics H/W...");
546
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900547 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
548
Dan Stoza9e56aa02015-11-02 13:00:03 -0800549 { // Autolock scope
550 Mutex::Autolock _l(mStateLock);
551
552 // initialize EGL for the default display
553 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
554 eglInitialize(mEGLDisplay, NULL, NULL);
555
556 // start the EventThread
557 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
558 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700559 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800560 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
561 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700562 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800563 mEventQueue.setEventThread(mSFEventThread);
564
Tim Murray22752852017-05-04 13:38:49 -0700565 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700566 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700567 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700568 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
569 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
570 }
Tim Murray22752852017-05-04 13:38:49 -0700571 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
572 ALOGE("Couldn't set SCHED_FIFO for EventThread");
573 }
Tim Murray41a38532016-06-22 12:42:10 -0700574
Dan Stoza9e56aa02015-11-02 13:00:03 -0800575 // Get a RenderEngine for the given display / config (can't fail)
576 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700577 HAL_PIXEL_FORMAT_RGBA_8888,
578 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800579 }
580
581 // Drop the state lock while we initialize the hardware composer. We drop
582 // the lock because on creation, it will call back into SurfaceFlinger to
583 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800584 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
585 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800586 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800587 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800588 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
589
Jesse Hall692c7232012-11-08 15:41:56 -0800590 Mutex::Autolock _l(mStateLock);
591
Steven Thomas050b2c82017-03-06 11:45:16 -0800592 if (useVrFlinger) {
593 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700594 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800595 mVrFlingerRequestsDisplay = requestDisplay;
596 signalTransaction();
597 };
598 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
599 vrFlingerRequestDisplayCallback);
600 if (!mVrFlinger) {
601 ALOGE("Failed to start vrflinger");
602 }
603 }
604
Mathias Agopian875d8e12013-06-07 15:35:48 -0700605 // retrieve the EGL context that was selected/created
606 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700607
Mathias Agopianda27af92012-09-13 18:17:13 -0700608 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
609 "couldn't create EGLContext");
610
Dan Stoza9e56aa02015-11-02 13:00:03 -0800611 // make the GLContext current so that we can create textures when creating
612 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700613 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700614
Jamie Gennisd1700752013-10-14 12:22:52 -0700615 mEventControlThread = new EventControlThread(this);
616 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
617
Mathias Agopian92a979a2012-08-02 18:32:23 -0700618 // initialize our drawing state
619 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700620
Andy McFadden13a082e2012-08-24 10:16:42 -0700621 // set initial conditions (e.g. unblank default device)
622 initializeDisplays();
623
Dan Stoza4e637772016-07-28 13:31:51 -0700624 mRenderEngine->primeCache();
625
Wei Wangf9b05ee2017-07-19 20:59:39 -0700626 // Inform native graphics APIs whether the present timestamp is supported:
627 if (getHwComposer().hasCapability(
628 HWC2::Capability::PresentFenceIsNotReliable)) {
629 mStartPropertySetThread = new StartPropertySetThread(false);
630 } else {
631 mStartPropertySetThread = new StartPropertySetThread(true);
632 }
633
634 if (mStartPropertySetThread->Start() != NO_ERROR) {
635 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800636 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800637
Dan Stoza9e56aa02015-11-02 13:00:03 -0800638 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700639}
640
Romain Guy11d63f42017-07-20 12:47:14 -0700641void SurfaceFlinger::readPersistentProperties() {
642 char value[PROPERTY_VALUE_MAX];
643
644 property_get("persist.sys.sf.color_saturation", value, "1.0");
645 mSaturation = atof(value);
646 ALOGV("Saturation is set to %.2f", mSaturation);
647}
648
Mathias Agopiana67e4182012-06-19 17:26:12 -0700649void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800650 // Start boot animation service by setting a property mailbox
651 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700652 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800653 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700654 if (mStartPropertySetThread->join() != NO_ERROR) {
655 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800656 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700657}
658
Mathias Agopian875d8e12013-06-07 15:35:48 -0700659size_t SurfaceFlinger::getMaxTextureSize() const {
660 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700661}
662
Mathias Agopian875d8e12013-06-07 15:35:48 -0700663size_t SurfaceFlinger::getMaxViewportDims() const {
664 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700665}
666
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800667// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800668
Jamie Gennis582270d2011-08-17 18:19:00 -0700669bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800670 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800671 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800672 return authenticateSurfaceTextureLocked(bufferProducer);
673}
674
675bool SurfaceFlinger::authenticateSurfaceTextureLocked(
676 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800677 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700678 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800679}
680
Brian Anderson6b376712017-04-04 10:51:39 -0700681status_t SurfaceFlinger::getSupportedFrameTimestamps(
682 std::vector<FrameEvent>* outSupported) const {
683 *outSupported = {
684 FrameEvent::REQUESTED_PRESENT,
685 FrameEvent::ACQUIRE,
686 FrameEvent::LATCH,
687 FrameEvent::FIRST_REFRESH_START,
688 FrameEvent::LAST_REFRESH_START,
689 FrameEvent::GPU_COMPOSITION_DONE,
690 FrameEvent::DEQUEUE_READY,
691 FrameEvent::RELEASE,
692 };
693 if (!getHwComposer().hasCapability(
694 HWC2::Capability::PresentFenceIsNotReliable)) {
695 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
696 }
697 return NO_ERROR;
698}
699
Dan Stoza7f7da322014-05-02 15:26:25 -0700700status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
701 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700702 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700703 return BAD_VALUE;
704 }
705
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500706 if (!display.get())
707 return NAME_NOT_FOUND;
708
Jesse Hall692c7232012-11-08 15:41:56 -0800709 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700710 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800711 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700712 type = i;
713 break;
714 }
715 }
716
717 if (type < 0) {
718 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700719 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700720
Mathias Agopian8b736f12012-08-13 17:54:26 -0700721 // TODO: Not sure if display density should handled by SF any longer
722 class Density {
723 static int getDensityFromProperty(char const* propName) {
724 char property[PROPERTY_VALUE_MAX];
725 int density = 0;
726 if (property_get(propName, property, NULL) > 0) {
727 density = atoi(property);
728 }
729 return density;
730 }
731 public:
732 static int getEmuDensity() {
733 return getDensityFromProperty("qemu.sf.lcd_density"); }
734 static int getBuildDensity() {
735 return getDensityFromProperty("ro.sf.lcd_density"); }
736 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700737
Dan Stoza7f7da322014-05-02 15:26:25 -0700738 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700739
Dan Stoza9e56aa02015-11-02 13:00:03 -0800740 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700741 DisplayInfo info = DisplayInfo();
742
Dan Stoza9e56aa02015-11-02 13:00:03 -0800743 float xdpi = hwConfig->getDpiX();
744 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700745
746 if (type == DisplayDevice::DISPLAY_PRIMARY) {
747 // The density of the device is provided by a build property
748 float density = Density::getBuildDensity() / 160.0f;
749 if (density == 0) {
750 // the build doesn't provide a density -- this is wrong!
751 // use xdpi instead
752 ALOGE("ro.sf.lcd_density must be defined as a build property");
753 density = xdpi / 160.0f;
754 }
755 if (Density::getEmuDensity()) {
756 // if "qemu.sf.lcd_density" is specified, it overrides everything
757 xdpi = ydpi = density = Density::getEmuDensity();
758 density /= 160.0f;
759 }
760 info.density = density;
761
762 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000763 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
764 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700765 } else {
766 // TODO: where should this value come from?
767 static const int TV_DENSITY = 213;
768 info.density = TV_DENSITY / 160.0f;
769 info.orientation = 0;
770 }
771
Dan Stoza9e56aa02015-11-02 13:00:03 -0800772 info.w = hwConfig->getWidth();
773 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700774 info.xdpi = xdpi;
775 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800776 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900777 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800778
Andy McFadden91b2ca82014-06-13 14:04:23 -0700779 // This is how far in advance a buffer must be queued for
780 // presentation at a given time. If you want a buffer to appear
781 // on the screen at time N, you must submit the buffer before
782 // (N - presentationDeadline).
783 //
784 // Normally it's one full refresh period (to give SF a chance to
785 // latch the buffer), but this can be reduced by configuring a
786 // DispSync offset. Any additional delays introduced by the hardware
787 // composer or panel must be accounted for here.
788 //
789 // We add an additional 1ms to allow for processing time and
790 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800791 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800792 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700793
794 // All non-virtual displays are currently considered secure.
795 info.secure = true;
796
Michael Wright28f24d02016-07-12 13:30:53 -0700797 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700798 }
799
Dan Stoza7f7da322014-05-02 15:26:25 -0700800 return NO_ERROR;
801}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700802
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800803status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700804 DisplayStatInfo* stats) {
805 if (stats == NULL) {
806 return BAD_VALUE;
807 }
808
809 // FIXME for now we always return stats for the primary display
810 memset(stats, 0, sizeof(*stats));
811 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
812 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
813 return NO_ERROR;
814}
815
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700816int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800817 if (display == NULL) {
818 ALOGE("%s : display is NULL", __func__);
819 return BAD_VALUE;
820 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700821
822 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700823 if (device != NULL) {
824 return device->getActiveConfig();
825 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700826
Dan Stoza24a42e92015-03-09 10:04:11 -0700827 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700828}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700829
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700830void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
831 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
832 this);
833 int32_t type = hw->getDisplayType();
834 int currentMode = hw->getActiveConfig();
835
836 if (mode == currentMode) {
837 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
838 return;
839 }
840
841 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
842 ALOGW("Trying to set config for virtual display");
843 return;
844 }
845
846 hw->setActiveConfig(mode);
847 getHwComposer().setActiveConfig(type, mode);
848}
849
850status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
851 class MessageSetActiveConfig: public MessageBase {
852 SurfaceFlinger& mFlinger;
853 sp<IBinder> mDisplay;
854 int mMode;
855 public:
856 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
857 int mode) :
858 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
859 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700860 Vector<DisplayInfo> configs;
861 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700862 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700863 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700864 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700865 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700866 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700867 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
868 if (hw == NULL) {
869 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700870 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700871 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
872 ALOGW("Attempt to set active config = %d for virtual display",
873 mMode);
874 } else {
875 mFlinger.setActiveConfigInternal(hw, mMode);
876 }
877 return true;
878 }
879 };
880 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
881 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700882 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700883}
Michael Wright28f24d02016-07-12 13:30:53 -0700884status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
885 Vector<android_color_mode_t>* outColorModes) {
886 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
887 return BAD_VALUE;
888 }
889
890 if (!display.get()) {
891 return NAME_NOT_FOUND;
892 }
893
894 int32_t type = NAME_NOT_FOUND;
895 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
896 if (display == mBuiltinDisplays[i]) {
897 type = i;
898 break;
899 }
900 }
901
902 if (type < 0) {
903 return type;
904 }
905
906 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
907 outColorModes->clear();
908 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
909
910 return NO_ERROR;
911}
912
913android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700914 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700915 if (device != nullptr) {
916 return device->getActiveColorMode();
917 }
918 return static_cast<android_color_mode_t>(BAD_VALUE);
919}
920
921void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
922 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700923 int32_t type = hw->getDisplayType();
924 android_color_mode_t currentMode = hw->getActiveColorMode();
925
926 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700927 return;
928 }
929
930 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
931 ALOGW("Trying to set config for virtual display");
932 return;
933 }
934
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600935 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
936 hw->getDisplayType());
937
Michael Wright28f24d02016-07-12 13:30:53 -0700938 hw->setActiveColorMode(mode);
939 getHwComposer().setActiveColorMode(type, mode);
940}
941
942
943status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
944 android_color_mode_t colorMode) {
945 class MessageSetActiveColorMode: public MessageBase {
946 SurfaceFlinger& mFlinger;
947 sp<IBinder> mDisplay;
948 android_color_mode_t mMode;
949 public:
950 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
951 android_color_mode_t mode) :
952 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
953 virtual bool handler() {
954 Vector<android_color_mode_t> modes;
955 mFlinger.getDisplayColorModes(mDisplay, &modes);
956 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
957 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600958 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
959 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700960 return true;
961 }
962 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
963 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600964 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
965 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700966 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600967 ALOGW("Attempt to set active color mode %s %d for virtual display",
968 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700969 } else {
970 mFlinger.setActiveColorModeInternal(hw, mMode);
971 }
972 return true;
973 }
974 };
975 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
976 postMessageSync(msg);
977 return NO_ERROR;
978}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700979
Svetoslavd85084b2014-03-20 10:28:31 -0700980status_t SurfaceFlinger::clearAnimationFrameStats() {
981 Mutex::Autolock _l(mStateLock);
982 mAnimFrameTracker.clearStats();
983 return NO_ERROR;
984}
985
986status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
987 Mutex::Autolock _l(mStateLock);
988 mAnimFrameTracker.getStats(outStats);
989 return NO_ERROR;
990}
991
Dan Stozac4f471e2016-03-24 09:31:08 -0700992status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
993 HdrCapabilities* outCapabilities) const {
994 Mutex::Autolock _l(mStateLock);
995
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700996 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -0700997 if (displayDevice == nullptr) {
998 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
999 return BAD_VALUE;
1000 }
1001
1002 std::unique_ptr<HdrCapabilities> capabilities =
1003 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1004 if (capabilities) {
1005 std::swap(*outCapabilities, *capabilities);
1006 } else {
1007 return BAD_VALUE;
1008 }
1009
1010 return NO_ERROR;
1011}
1012
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001013status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1014 if (enable == mInjectVSyncs) {
1015 return NO_ERROR;
1016 }
1017
1018 if (enable) {
1019 mInjectVSyncs = enable;
1020 ALOGV("VSync Injections enabled");
1021 if (mVSyncInjector.get() == nullptr) {
1022 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001023 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001024 }
1025 mEventQueue.setEventThread(mInjectorEventThread);
1026 } else {
1027 mInjectVSyncs = enable;
1028 ALOGV("VSync Injections disabled");
1029 mEventQueue.setEventThread(mSFEventThread);
1030 mVSyncInjector.clear();
1031 }
1032 return NO_ERROR;
1033}
1034
1035status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1036 if (!mInjectVSyncs) {
1037 ALOGE("VSync Injections not enabled");
1038 return BAD_VALUE;
1039 }
1040 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1041 ALOGV("Injecting VSync inside SurfaceFlinger");
1042 mVSyncInjector->onInjectSyncEvent(when);
1043 }
1044 return NO_ERROR;
1045}
1046
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001047// ----------------------------------------------------------------------------
1048
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001049sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1050 ISurfaceComposer::VsyncSource vsyncSource) {
1051 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1052 return mSFEventThread->createEventConnection();
1053 } else {
1054 return mEventThread->createEventConnection();
1055 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001056}
1057
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001058// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001059
1060void SurfaceFlinger::waitForEvent() {
1061 mEventQueue.waitMessage();
1062}
1063
1064void SurfaceFlinger::signalTransaction() {
1065 mEventQueue.invalidate();
1066}
1067
1068void SurfaceFlinger::signalLayerUpdate() {
1069 mEventQueue.invalidate();
1070}
1071
1072void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001073 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001074 mEventQueue.refresh();
1075}
1076
1077status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001078 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001079 return mEventQueue.postMessage(msg, reltime);
1080}
1081
1082status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001083 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001084 status_t res = mEventQueue.postMessage(msg, reltime);
1085 if (res == NO_ERROR) {
1086 msg->wait();
1087 }
1088 return res;
1089}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001090
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001091void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001092 do {
1093 waitForEvent();
1094 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001095}
1096
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001097void SurfaceFlinger::enableHardwareVsync() {
1098 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001099 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001100 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001101 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1102 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001103 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001104 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001105}
1106
Jesse Hall948fe0c2013-10-14 12:56:09 -07001107void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001108 Mutex::Autolock _l(mHWVsyncLock);
1109
Jesse Hall948fe0c2013-10-14 12:56:09 -07001110 if (makeAvailable) {
1111 mHWVsyncAvailable = true;
1112 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001113 // Hardware vsync is not currently available, so abort the resync
1114 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001115 return;
1116 }
1117
Dan Stoza9e56aa02015-11-02 13:00:03 -08001118 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1119 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001120
1121 mPrimaryDispSync.reset();
1122 mPrimaryDispSync.setPeriod(period);
1123
1124 if (!mPrimaryHWVsyncEnabled) {
1125 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001126 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1127 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001128 mPrimaryHWVsyncEnabled = true;
1129 }
1130}
1131
Jesse Hall948fe0c2013-10-14 12:56:09 -07001132void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001133 Mutex::Autolock _l(mHWVsyncLock);
1134 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001135 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1136 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001137 mPrimaryDispSync.endResync();
1138 mPrimaryHWVsyncEnabled = false;
1139 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001140 if (makeUnavailable) {
1141 mHWVsyncAvailable = false;
1142 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001143}
1144
Tim Murray4a4e4a22016-04-19 16:29:23 +00001145void SurfaceFlinger::resyncWithRateLimit() {
1146 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001147
1148 // No explicit locking is needed here since EventThread holds a lock while calling this method
1149 static nsecs_t sLastResyncAttempted = 0;
1150 const nsecs_t now = systemTime();
1151 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001152 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001153 }
Dan Stoza57164302017-05-08 14:03:54 -07001154 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001155}
1156
Steven Thomas3cfac282017-02-06 12:29:30 -08001157void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1158 nsecs_t timestamp) {
1159 Mutex::Autolock lock(mStateLock);
1160 // Ignore any vsyncs from the non-active hardware composer.
1161 if (composer != mHwc) {
1162 return;
1163 }
1164
Jamie Gennisd1700752013-10-14 12:22:52 -07001165 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001166
Jamie Gennisd1700752013-10-14 12:22:52 -07001167 { // Scope for the lock
1168 Mutex::Autolock _l(mHWVsyncLock);
1169 if (type == 0 && mPrimaryHWVsyncEnabled) {
1170 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001171 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001172 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001173
1174 if (needsHwVsync) {
1175 enableHardwareVsync();
1176 } else {
1177 disableHardwareVsync(false);
1178 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001179}
1180
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001181void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001182 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001183 *compositorTiming = mCompositorTiming;
1184}
1185
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001186void SurfaceFlinger::createDefaultDisplayDevice() {
1187 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1188 wp<IBinder> token = mBuiltinDisplays[type];
1189
1190 // All non-virtual displays are currently considered secure.
1191 const bool isSecure = true;
1192
1193 sp<IGraphicBufferProducer> producer;
1194 sp<IGraphicBufferConsumer> consumer;
1195 BufferQueue::createBufferQueue(&producer, &consumer);
1196
1197 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1198
1199 bool hasWideColorModes = false;
1200 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1201 for (android_color_mode_t colorMode : modes) {
1202 switch (colorMode) {
1203 case HAL_COLOR_MODE_DISPLAY_P3:
1204 case HAL_COLOR_MODE_ADOBE_RGB:
1205 case HAL_COLOR_MODE_DCI_P3:
1206 hasWideColorModes = true;
1207 break;
1208 default:
1209 break;
1210 }
1211 }
1212 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1213 token, fbs, producer, mRenderEngine->getEGLConfig(),
1214 hasWideColorModes && hasWideColorDisplay);
1215 mDisplays.add(token, hw);
1216 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1217 if (hasWideColorModes && hasWideColorDisplay) {
1218 defaultColorMode = HAL_COLOR_MODE_SRGB;
1219 }
1220 setActiveColorModeInternal(hw, defaultColorMode);
1221}
1222
1223void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001224 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001225
1226 if (composer->isUsingVrComposer()) {
1227 // We handle initializing the primary display device for the VR
1228 // window manager hwc explicitly at the time of transition.
1229 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1230 ALOGE("External displays are not supported by the vr hardware composer.");
1231 }
1232 return;
1233 }
1234
Dan Stoza9e56aa02015-11-02 13:00:03 -08001235 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1236 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001237 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1238 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001239 } else {
1240 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001241 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001242 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001243 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001244 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001245 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1246 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001247 }
1248 setTransactionFlags(eDisplayTransactionNeeded);
1249
Andy McFadden9e9689c2012-10-10 18:17:51 -07001250 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001251 }
Mathias Agopian86303202012-07-24 22:46:10 -07001252}
1253
Steven Thomas3cfac282017-02-06 12:29:30 -08001254void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1255 Mutex::Autolock lock(mStateLock);
1256 if (composer == mHwc) {
1257 repaintEverything();
1258 } else {
1259 // This isn't from our current hardware composer. If it's a callback
1260 // from the real composer, forward the refresh request to vr
1261 // flinger. Otherwise ignore it.
1262 if (!composer->isUsingVrComposer()) {
1263 mVrFlinger->OnHardwareComposerRefresh();
1264 }
1265 }
1266}
1267
Dan Stoza9e56aa02015-11-02 13:00:03 -08001268void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001269 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001270 getHwComposer().setVsyncEnabled(disp,
1271 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001272}
1273
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001274// Note: it is assumed the caller holds |mStateLock| when this is called
1275void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001276 disableHardwareVsync(true);
1277 clearHwcLayers(mDrawingState.layersSortedByZ);
1278 clearHwcLayers(mCurrentState.layersSortedByZ);
Steven Thomasf5a5f6e2017-07-17 13:59:23 -07001279 for (size_t disp = 0; disp < mDisplays.size(); ++disp) {
1280 clearHwcLayers(mDisplays[disp]->getVisibleLayersSortedByZ());
1281 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001282 // Clear the drawing state so that the logic inside of
1283 // handleTransactionLocked will fire. It will determine the delta between
1284 // mCurrentState and mDrawingState and re-apply all changes when we make the
1285 // transition.
1286 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001287 // Release virtual display hwcId during vr mode transition.
1288 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1289 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1290 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1291 displayDevice->disconnect(getHwComposer());
1292 }
1293 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001294 mDisplays.clear();
1295}
1296
Steven Thomas050b2c82017-03-06 11:45:16 -08001297void SurfaceFlinger::updateVrFlinger() {
1298 if (!mVrFlinger)
1299 return;
1300 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1301 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001302 return;
1303 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001304
Steven Thomas050b2c82017-03-06 11:45:16 -08001305 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001306 // Construct new HWComposer without holding any locks.
1307 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001308
1309 // Set up the event handlers. This step is neccessary to initialize the internal state of
1310 // the hardware composer object properly. Our callbacks are designed such that if they are
1311 // triggered between now and the point where the display is properly re-initialized, they
1312 // will not have any effect, so this is safe to do here, before the lock is aquired.
1313 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001314 ALOGV("Vr HWC created");
1315 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001316
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001317 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001318
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001319 if (vrFlingerRequestsDisplay) {
1320 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001321
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001322 mHwc = mVrHwc;
1323 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001324
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001325 } else {
1326 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001327
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001328 resetHwcLocked();
1329
1330 mHwc = mRealHwc;
1331 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001332 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001333
1334 mVisibleRegionsDirty = true;
1335 invalidateHwcGeometry();
1336
1337 // Explicitly re-initialize the primary display. This is because some other
1338 // parts of this class rely on the primary display always being available.
1339 createDefaultDisplayDevice();
1340
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001341 // Re-enable default display.
1342 sp<LambdaMessage> requestMessage = new LambdaMessage([&]() {
1343 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1344 setPowerModeInternal(hw, HWC_POWER_MODE_NORMAL);
1345
1346 // Reset the timing values to account for the period of the swapped in HWC
1347 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1348 const nsecs_t period = activeConfig->getVsyncPeriod();
1349 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1350
1351 // Use phase of 0 since phase is not known.
1352 // Use latency of 0, which will snap to the ideal latency.
1353 setCompositorTimingSnapped(0, period, 0);
1354 });
1355 postMessageAsync(requestMessage);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001356
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001357 android_atomic_or(1, &mRepaintEverything);
1358 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001359}
1360
Mathias Agopian4fec8732012-06-29 14:12:52 -07001361void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001362 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001363 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001364 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001365 bool frameMissed = !mHadClientComposition &&
1366 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001367 (mPreviousPresentFence->getSignalTime() ==
1368 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001369 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001370 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001371 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001372 signalLayerUpdate();
1373 break;
1374 }
1375
Steven Thomas050b2c82017-03-06 11:45:16 -08001376 // Now that we're going to make it to the handleMessageTransaction()
1377 // call below it's safe to call updateVrFlinger(), which will
1378 // potentially trigger a display handoff.
1379 updateVrFlinger();
1380
Dan Stoza6b9454d2014-11-07 16:00:59 -08001381 bool refreshNeeded = handleMessageTransaction();
1382 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001383 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001384 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001385 // Signal a refresh if a transaction modified the window state,
1386 // a new buffer was latched, or if HWC has requested a full
1387 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001388 signalRefresh();
1389 }
1390 break;
1391 }
1392 case MessageQueue::REFRESH: {
1393 handleMessageRefresh();
1394 break;
1395 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001396 }
1397}
1398
Dan Stoza6b9454d2014-11-07 16:00:59 -08001399bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001400 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001401 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001402 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001403 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001404 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001405 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001406}
1407
Dan Stoza6b9454d2014-11-07 16:00:59 -08001408bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001409 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001410 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001411}
1412
1413void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001414 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001415
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001416 mRefreshPending = false;
1417
Pablo Ceballos40845df2016-01-25 17:41:15 -08001418 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001419
Brian Andersond6927fb2016-07-23 23:37:30 -07001420 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001421 rebuildLayerStacks();
1422 setUpHWComposer();
1423 doDebugFlashRegions();
1424 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001425 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001426
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001427 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001428
1429 mHadClientComposition = false;
1430 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1431 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1432 mHadClientComposition = mHadClientComposition ||
1433 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1434 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001435
Dan Stoza9e56aa02015-11-02 13:00:03 -08001436 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001437}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001438
Mathias Agopiancd60f992012-08-16 16:28:27 -07001439void SurfaceFlinger::doDebugFlashRegions()
1440{
1441 // is debugging enabled
1442 if (CC_LIKELY(!mDebugRegion))
1443 return;
1444
1445 const bool repaintEverything = mRepaintEverything;
1446 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1447 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001448 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001449 // transform the dirty region into this screen's coordinate space
1450 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1451 if (!dirtyRegion.isEmpty()) {
1452 // redraw the whole screen
1453 doComposeSurfaces(hw, Region(hw->bounds()));
1454
1455 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001456 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001457 RenderEngine& engine(getRenderEngine());
1458 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1459
Mathias Agopianda27af92012-09-13 18:17:13 -07001460 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001461 }
1462 }
1463 }
1464
1465 postFramebuffer();
1466
1467 if (mDebugRegion > 1) {
1468 usleep(mDebugRegion * 1000);
1469 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001470
Dan Stoza9e56aa02015-11-02 13:00:03 -08001471 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001472 auto& displayDevice = mDisplays[displayId];
1473 if (!displayDevice->isDisplayOn()) {
1474 continue;
1475 }
1476
1477 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001478 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1479 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001480 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001481}
1482
Brian Andersond6927fb2016-07-23 23:37:30 -07001483void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001484{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001485 ATRACE_CALL();
1486 ALOGV("preComposition");
1487
Mathias Agopiancd60f992012-08-16 16:28:27 -07001488 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001489 mDrawingState.traverseInZOrder([&](Layer* layer) {
1490 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001491 needExtraInvalidate = true;
1492 }
Robert Carr2047fae2016-11-28 14:09:09 -08001493 });
1494
Mathias Agopiancd60f992012-08-16 16:28:27 -07001495 if (needExtraInvalidate) {
1496 signalLayerUpdate();
1497 }
1498}
1499
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001500void SurfaceFlinger::updateCompositorTiming(
1501 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1502 std::shared_ptr<FenceTime>& presentFenceTime) {
1503 // Update queue of past composite+present times and determine the
1504 // most recently known composite to present latency.
1505 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1506 nsecs_t compositeToPresentLatency = -1;
1507 while (!mCompositePresentTimes.empty()) {
1508 CompositePresentTime& cpt = mCompositePresentTimes.front();
1509 // Cached values should have been updated before calling this method,
1510 // which helps avoid duplicate syscalls.
1511 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1512 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1513 break;
1514 }
1515 compositeToPresentLatency = displayTime - cpt.composite;
1516 mCompositePresentTimes.pop();
1517 }
1518
1519 // Don't let mCompositePresentTimes grow unbounded, just in case.
1520 while (mCompositePresentTimes.size() > 16) {
1521 mCompositePresentTimes.pop();
1522 }
1523
Brian Andersond0010582017-03-07 13:20:31 -08001524 setCompositorTimingSnapped(
1525 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1526}
1527
1528void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1529 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001530 // Integer division and modulo round toward 0 not -inf, so we need to
1531 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001532 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001533 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1534 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1535
Brian Andersond0010582017-03-07 13:20:31 -08001536 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1537 if (idealLatency <= 0) {
1538 idealLatency = vsyncInterval;
1539 }
1540
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001541 // Snap the latency to a value that removes scheduling jitter from the
1542 // composition and present times, which often have >1ms of jitter.
1543 // Reducing jitter is important if an app attempts to extrapolate
1544 // something (such as user input) to an accurate diasplay time.
1545 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1546 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001547 nsecs_t bias = vsyncInterval / 2;
1548 int64_t extraVsyncs =
1549 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1550 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1551 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001552
Brian Andersond0010582017-03-07 13:20:31 -08001553 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001554 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1555 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001556 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001557}
1558
1559void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001561 ATRACE_CALL();
1562 ALOGV("postComposition");
1563
Brian Anderson3546a3f2016-07-14 11:51:14 -07001564 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001565 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001566 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001567 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001568 }
1569
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001570 // |mStateLock| not needed as we are on the main thread
1571 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001572
1573 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1574 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1575 glCompositionDoneFenceTime =
1576 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1577 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1578 } else {
1579 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1580 }
1581 mGlCompositionDoneTimeline.updateSignalTimes();
1582
Brian Anderson4e606e32017-03-16 15:34:57 -07001583 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1584 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1585 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001586 mDisplayTimeline.updateSignalTimes();
1587
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001588 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1589 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1590
1591 // We use the refreshStartTime which might be sampled a little later than
1592 // when we started doing work for this frame, but that should be okay
1593 // since updateCompositorTiming has snapping logic.
1594 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001595 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001596 CompositorTiming compositorTiming;
1597 {
1598 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1599 compositorTiming = mCompositorTiming;
1600 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001601
Robert Carr2047fae2016-11-28 14:09:09 -08001602 mDrawingState.traverseInZOrder([&](Layer* layer) {
1603 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001604 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001605 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001606 recordBufferingStats(layer->getName().string(),
1607 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001608 }
Robert Carr2047fae2016-11-28 14:09:09 -08001609 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001610
Brian Anderson4e606e32017-03-16 15:34:57 -07001611 if (presentFence->isValid()) {
1612 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001613 enableHardwareVsync();
1614 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001615 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001616 }
1617 }
1618
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001619 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001620 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001621 enableHardwareVsync();
1622 }
1623 }
1624
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001625 if (mAnimCompositionPending) {
1626 mAnimCompositionPending = false;
1627
Brian Anderson4e606e32017-03-16 15:34:57 -07001628 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001629 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001630 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001631 } else {
1632 // The HWC doesn't support present fences, so use the refresh
1633 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001634 nsecs_t presentTime =
1635 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001636 mAnimFrameTracker.setActualPresentTime(presentTime);
1637 }
1638 mAnimFrameTracker.advanceFrame();
1639 }
Dan Stozab90cf072015-03-05 11:05:59 -08001640
1641 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1642 return;
1643 }
1644
1645 nsecs_t currentTime = systemTime();
1646 if (mHasPoweredOff) {
1647 mHasPoweredOff = false;
1648 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001649 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001651 if (numPeriods < NUM_BUCKETS - 1) {
1652 mFrameBuckets[numPeriods] += elapsedTime;
1653 } else {
1654 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1655 }
1656 mTotalTime += elapsedTime;
1657 }
1658 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001659}
1660
1661void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001662 ATRACE_CALL();
1663 ALOGV("rebuildLayerStacks");
1664
Mathias Agopiancd60f992012-08-16 16:28:27 -07001665 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001666 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1667 ATRACE_CALL();
1668 mVisibleRegionsDirty = false;
1669 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001670
Jeff Sharkey76488112017-02-27 14:15:18 -07001671 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1672 Region opaqueRegion;
1673 Region dirtyRegion;
1674 Vector<sp<Layer>> layersSortedByZ;
1675 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1676 const Transform& tr(displayDevice->getTransform());
1677 const Rect bounds(displayDevice->getBounds());
1678 if (displayDevice->isDisplayOn()) {
1679 computeVisibleRegions(
1680 displayDevice->getLayerStack(), dirtyRegion,
1681 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001682
Jeff Sharkey76488112017-02-27 14:15:18 -07001683 mDrawingState.traverseInZOrder([&](Layer* layer) {
1684 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1685 Region drawRegion(tr.transform(
1686 layer->visibleNonTransparentRegion));
1687 drawRegion.andSelf(bounds);
1688 if (!drawRegion.isEmpty()) {
1689 layersSortedByZ.add(layer);
1690 } else {
1691 // Clear out the HWC layer if this layer was
1692 // previously visible, but no longer is
1693 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1694 nullptr);
1695 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001696 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001697 // WM changes displayDevice->layerStack upon sleep/awake.
1698 // Here we make sure we delete the HWC layers even if
1699 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001700 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1701 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001702 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001703 });
1704 }
1705 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1706 displayDevice->undefinedRegion.set(bounds);
1707 displayDevice->undefinedRegion.subtractSelf(
1708 tr.transform(opaqueRegion));
1709 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001710 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001711 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001712}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001713
Romain Guy0147a172017-06-01 13:53:56 -07001714mat4 SurfaceFlinger::computeSaturationMatrix() const {
1715 if (mSaturation == 1.0f) {
1716 return mat4();
1717 }
1718
1719 // Rec.709 luma coefficients
1720 float3 luminance{0.213f, 0.715f, 0.072f};
1721 luminance *= 1.0f - mSaturation;
1722 return mat4(
1723 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1724 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1725 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1726 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1727 );
1728}
1729
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001730// pickColorMode translates a given dataspace into the best available color mode.
1731// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001732android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001733 switch (dataSpace) {
1734 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1735 // system expects.
1736 case HAL_DATASPACE_UNKNOWN:
1737 case HAL_DATASPACE_SRGB:
1738 case HAL_DATASPACE_V0_SRGB:
1739 return HAL_COLOR_MODE_SRGB;
1740 break;
1741
1742 case HAL_DATASPACE_DISPLAY_P3:
1743 return HAL_COLOR_MODE_DISPLAY_P3;
1744 break;
1745
1746 default:
1747 // TODO (courtneygo): Do we want to assert an error here?
1748 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1749 dataSpace);
1750 return HAL_COLOR_MODE_SRGB;
1751 break;
1752 }
1753}
1754
Romain Guy0147a172017-06-01 13:53:56 -07001755android_dataspace SurfaceFlinger::bestTargetDataSpace(
1756 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001757 // Only support sRGB and Display-P3 right now.
1758 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1759 return HAL_DATASPACE_DISPLAY_P3;
1760 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001761 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1762 return HAL_DATASPACE_DISPLAY_P3;
1763 }
1764 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1765 return HAL_DATASPACE_DISPLAY_P3;
1766 }
1767
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001768 return HAL_DATASPACE_V0_SRGB;
1769}
1770
Mathias Agopiancd60f992012-08-16 16:28:27 -07001771void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001772 ATRACE_CALL();
1773 ALOGV("setUpHWComposer");
1774
Jesse Hall028dc8f2013-08-20 16:35:32 -07001775 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001776 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1777 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1778 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1779
1780 // If nothing has changed (!dirty), don't recompose.
1781 // If something changed, but we don't currently have any visible layers,
1782 // and didn't when we last did a composition, then skip it this time.
1783 // The second rule does two things:
1784 // - When all layers are removed from a display, we'll emit one black
1785 // frame, then nothing more until we get new layers.
1786 // - When a display is created with a private layer stack, we won't
1787 // emit any black frames until a layer is added to the layer stack.
1788 bool mustRecompose = dirty && !(empty && wasEmpty);
1789
1790 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1791 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1792 mustRecompose ? "doing" : "skipping",
1793 dirty ? "+" : "-",
1794 empty ? "+" : "-",
1795 wasEmpty ? "+" : "-");
1796
Dan Stoza71433162014-02-04 16:22:36 -08001797 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001798
1799 if (mustRecompose) {
1800 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1801 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001802 }
1803
Dan Stoza9e56aa02015-11-02 13:00:03 -08001804 // build the h/w work list
1805 if (CC_UNLIKELY(mGeometryInvalid)) {
1806 mGeometryInvalid = false;
1807 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1808 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1809 const auto hwcId = displayDevice->getHwcDisplayId();
1810 if (hwcId >= 0) {
1811 const Vector<sp<Layer>>& currentLayers(
1812 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001813 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001814 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001815 if (!layer->hasHwcLayer(hwcId)) {
1816 auto hwcLayer = mHwc->createLayer(hwcId);
1817 if (hwcLayer) {
1818 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1819 } else {
1820 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001821 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001822 }
1823 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001824
Robert Carrae060832016-11-28 10:51:00 -08001825 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001826 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001827 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001828 }
1829 }
1830 }
1831 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001832 }
Riley Andrews03414a12014-07-01 14:22:59 -07001833
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001834
Romain Guy0147a172017-06-01 13:53:56 -07001835 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001836
Dan Stoza9e56aa02015-11-02 13:00:03 -08001837 // Set the per-frame data
1838 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1839 auto& displayDevice = mDisplays[displayId];
1840 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001841
Dan Stoza9e56aa02015-11-02 13:00:03 -08001842 if (hwcId < 0) {
1843 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001844 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001845 if (colorMatrix != mPreviousColorMatrix) {
1846 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1847 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1848 "display %zd: %d", displayId, result);
1849 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001850 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1851 layer->setPerFrameData(displayDevice);
1852 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001853
1854 if (hasWideColorDisplay) {
1855 android_color_mode newColorMode;
1856 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1857
1858 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1859 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1860 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1861 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1862 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1863 }
1864 newColorMode = pickColorMode(newDataSpace);
1865
1866 setActiveColorModeInternal(displayDevice, newColorMode);
1867 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001868 }
1869
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001870 mPreviousColorMatrix = colorMatrix;
1871
Dan Stoza9e56aa02015-11-02 13:00:03 -08001872 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001873 auto& displayDevice = mDisplays[displayId];
1874 if (!displayDevice->isDisplayOn()) {
1875 continue;
1876 }
1877
1878 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001879 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1880 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001881 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001882}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001883
Mathias Agopiancd60f992012-08-16 16:28:27 -07001884void SurfaceFlinger::doComposition() {
1885 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 ALOGV("doComposition");
1887
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001888 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001889 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001890 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001891 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001892 // transform the dirty region into this screen's coordinate space
1893 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001894
1895 // repaint the framebuffer (if needed)
1896 doDisplayComposition(hw, dirtyRegion);
1897
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898 hw->dirtyRegion.clear();
1899 hw->flip(hw->swapRegion);
1900 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001901 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001902 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001903 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001904}
1905
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001906void SurfaceFlinger::postFramebuffer()
1907{
Mathias Agopian841cde52012-03-01 15:44:37 -08001908 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001909 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001910
Mathias Agopiana44b0412011-10-16 18:46:35 -07001911 const nsecs_t now = systemTime();
1912 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001913
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1915 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001916 if (!displayDevice->isDisplayOn()) {
1917 continue;
1918 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001919 const auto hwcId = displayDevice->getHwcDisplayId();
1920 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001921 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001922 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001923 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001924 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1926 sp<Fence> releaseFence = Fence::NO_FENCE;
1927 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1928 releaseFence = displayDevice->getClientTargetAcquireFence();
1929 } else {
1930 auto hwcLayer = layer->getHwcLayer(hwcId);
1931 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001932 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 layer->onLayerDisplayed(releaseFence);
1934 }
1935 if (hwcId >= 0) {
1936 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001937 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001938 }
1939
Mathias Agopiana44b0412011-10-16 18:46:35 -07001940 mLastSwapBufferTime = systemTime() - now;
1941 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001942
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001943 // |mStateLock| not needed as we are on the main thread
1944 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001945 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1946 logFrameStats();
1947 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001948}
1949
Mathias Agopian87baae12012-07-31 12:38:26 -07001950void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001951{
Mathias Agopian841cde52012-03-01 15:44:37 -08001952 ATRACE_CALL();
1953
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001954 // here we keep a copy of the drawing state (that is the state that's
1955 // going to be overwritten by handleTransactionLocked()) outside of
1956 // mStateLock so that the side-effects of the State assignment
1957 // don't happen with mStateLock held (which can cause deadlocks).
1958 State drawingState(mDrawingState);
1959
Mathias Agopianca4d3602011-05-19 15:38:14 -07001960 Mutex::Autolock _l(mStateLock);
1961 const nsecs_t now = systemTime();
1962 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001963
Mathias Agopianca4d3602011-05-19 15:38:14 -07001964 // Here we're guaranteed that some transaction flags are set
1965 // so we can call handleTransactionLocked() unconditionally.
1966 // We call getTransactionFlags(), which will also clear the flags,
1967 // with mStateLock held to guarantee that mCurrentState won't change
1968 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001969
Mathias Agopiane57f2922012-08-09 16:29:12 -07001970 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001971 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001972
Mathias Agopianca4d3602011-05-19 15:38:14 -07001973 mLastTransactionTime = systemTime() - now;
1974 mDebugInTransaction = 0;
1975 invalidateHwcGeometry();
1976 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001977}
1978
Mathias Agopian87baae12012-07-31 12:38:26 -07001979void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001980{
Dan Stoza7dde5992015-05-22 09:51:44 -07001981 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001982 mCurrentState.traverseInZOrder([](Layer* layer) {
1983 layer->notifyAvailableFrames();
1984 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001985
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001986 /*
1987 * Traversal of the children
1988 * (perform the transaction for each of them if needed)
1989 */
1990
Mathias Agopian3559b072012-08-15 13:46:03 -07001991 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001992 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001993 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001994 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001995
1996 const uint32_t flags = layer->doTransaction(0);
1997 if (flags & Layer::eVisibleRegion)
1998 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001999 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002000 }
2001
2002 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002003 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002004 */
2005
Mathias Agopiane57f2922012-08-09 16:29:12 -07002006 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002007 // here we take advantage of Vector's copy-on-write semantics to
2008 // improve performance by skipping the transaction entirely when
2009 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002010 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2011 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002012 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002013 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002014 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002015 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002016
2017 // find the displays that were removed
2018 // (ie: in drawing state but not in current state)
2019 // also handle displays that changed
2020 // (ie: displays that are in both lists)
2021 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002022 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2023 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002024 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002025 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002026 // Call makeCurrent() on the primary display so we can
2027 // be sure that nothing associated with this display
2028 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002029 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002030 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002031 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002032 if (hw != NULL)
2033 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002034 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002035 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002036 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002037 } else {
2038 ALOGW("trying to remove the main display");
2039 }
2040 } else {
2041 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002042 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002043 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002044 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2045 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002046 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002047 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002048 // recreating the DisplayDevice, so we just remove it
2049 // from the drawing state, so that it get re-added
2050 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002051 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002052 if (hw != NULL)
2053 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002054 mDisplays.removeItem(display);
2055 mDrawingState.displays.removeItemsAt(i);
2056 dc--; i--;
2057 // at this point we must loop to the next item
2058 continue;
2059 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002060
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002061 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002062 if (disp != NULL) {
2063 if (state.layerStack != draw[i].layerStack) {
2064 disp->setLayerStack(state.layerStack);
2065 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002066 if ((state.orientation != draw[i].orientation)
2067 || (state.viewport != draw[i].viewport)
2068 || (state.frame != draw[i].frame))
2069 {
2070 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002071 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002072 }
Michael Lentine47e45402014-07-18 15:34:25 -07002073 if (state.width != draw[i].width || state.height != draw[i].height) {
2074 disp->setDisplaySize(state.width, state.height);
2075 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002076 }
2077 }
2078 }
2079
2080 // find displays that were added
2081 // (ie: in current state but not in drawing state)
2082 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002083 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002084 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002085
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002086 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002087 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002088 sp<IGraphicBufferProducer> bqProducer;
2089 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002090 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002091
Dan Stoza9e56aa02015-11-02 13:00:03 -08002092 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002093 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002094 // Virtual displays without a surface are dormant:
2095 // they have external state (layer stack, projection,
2096 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002097 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002098
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002099 // Allow VR composer to use virtual displays.
2100 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002101 int width = 0;
2102 int status = state.surface->query(
2103 NATIVE_WINDOW_WIDTH, &width);
2104 ALOGE_IF(status != NO_ERROR,
2105 "Unable to query width (%d)", status);
2106 int height = 0;
2107 status = state.surface->query(
2108 NATIVE_WINDOW_HEIGHT, &height);
2109 ALOGE_IF(status != NO_ERROR,
2110 "Unable to query height (%d)", status);
2111 int intFormat = 0;
2112 status = state.surface->query(
2113 NATIVE_WINDOW_FORMAT, &intFormat);
2114 ALOGE_IF(status != NO_ERROR,
2115 "Unable to query format (%d)", status);
2116 auto format = static_cast<android_pixel_format_t>(
2117 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002118
Dan Stoza8cf150a2016-08-02 10:27:31 -07002119 mHwc->allocateVirtualDisplay(width, height, &format,
2120 &hwcId);
2121 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002122
Dan Stoza5cf424b2016-05-20 14:02:39 -07002123 // TODO: Plumb requested format back up to consumer
2124
Dan Stoza9e56aa02015-11-02 13:00:03 -08002125 sp<VirtualDisplaySurface> vds =
2126 new VirtualDisplaySurface(*mHwc,
2127 hwcId, state.surface, bqProducer,
2128 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002129
2130 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002131 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002132 }
2133 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002134 ALOGE_IF(state.surface!=NULL,
2135 "adding a supported display, but rendering "
2136 "surface is provided (%p), ignoring it",
2137 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002138
2139 hwcId = state.type;
2140 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2141 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002142 }
2143
2144 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002145 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002146 sp<DisplayDevice> hw =
2147 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2148 dispSurface, producer,
2149 mRenderEngine->getEGLConfig(),
2150 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002151 hw->setLayerStack(state.layerStack);
2152 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002153 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002154 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002155 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002156 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002157 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002158 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002159 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002160 }
2161 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002162 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002163 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002164
Mathias Agopian84300952012-11-21 16:02:13 -08002165 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2166 // The transform hint might have changed for some layers
2167 // (either because a display has changed, or because a layer
2168 // as changed).
2169 //
2170 // Walk through all the layers in currentLayers,
2171 // and update their transform hint.
2172 //
2173 // If a layer is visible only on a single display, then that
2174 // display is used to calculate the hint, otherwise we use the
2175 // default display.
2176 //
2177 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2178 // the hint is set before we acquire a buffer from the surface texture.
2179 //
2180 // NOTE: layer transactions have taken place already, so we use their
2181 // drawing state. However, SurfaceFlinger's own transaction has not
2182 // happened yet, so we must use the current state layer list
2183 // (soon to become the drawing state list).
2184 //
2185 sp<const DisplayDevice> disp;
2186 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002187 bool first = true;
2188 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002189 // NOTE: we rely on the fact that layers are sorted by
2190 // layerStack first (so we don't have to traverse the list
2191 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002192 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002193 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002194 currentlayerStack = layerStack;
2195 // figure out if this layerstack is mirrored
2196 // (more than one display) if so, pick the default display,
2197 // if not, pick the only display it's on.
2198 disp.clear();
2199 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2200 sp<const DisplayDevice> hw(mDisplays[dpy]);
2201 if (hw->getLayerStack() == currentlayerStack) {
2202 if (disp == NULL) {
2203 disp = hw;
2204 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002205 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002206 break;
2207 }
2208 }
2209 }
2210 }
Chet Haase91d25932013-04-11 15:24:55 -07002211 if (disp == NULL) {
2212 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2213 // redraw after transform hint changes. See bug 8508397.
2214
2215 // could be null when this layer is using a layerStack
2216 // that is not visible on any display. Also can occur at
2217 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002218 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002219 }
Chet Haase91d25932013-04-11 15:24:55 -07002220 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002221
2222 first = false;
2223 });
Mathias Agopian84300952012-11-21 16:02:13 -08002224 }
2225
2226
Mathias Agopian3559b072012-08-15 13:46:03 -07002227 /*
2228 * Perform our own transaction if needed
2229 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002230
2231 if (mLayersAdded) {
2232 mLayersAdded = false;
2233 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002234 mVisibleRegionsDirty = true;
2235 }
2236
2237 // some layers might have been removed, so
2238 // we need to update the regions they're exposing.
2239 if (mLayersRemoved) {
2240 mLayersRemoved = false;
2241 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002242 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002243 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002244 // this layer is not visible anymore
2245 // TODO: we could traverse the tree from front to back and
2246 // compute the actual visible region
2247 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002248 Region visibleReg;
2249 visibleReg.set(layer->computeScreenBounds());
2250 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002251 }
Robert Carr2047fae2016-11-28 14:09:09 -08002252 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002253 }
2254
2255 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002256
2257 updateCursorAsync();
2258}
2259
2260void SurfaceFlinger::updateCursorAsync()
2261{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002262 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2263 auto& displayDevice = mDisplays[displayId];
2264 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002265 continue;
2266 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002267
2268 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2269 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002270 }
2271 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002272}
2273
2274void SurfaceFlinger::commitTransaction()
2275{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002276 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002277 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002278 for (const auto& l : mLayersPendingRemoval) {
2279 recordBufferingStats(l->getName().string(),
2280 l->getOccupancyHistory(true));
2281 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002282 }
2283 mLayersPendingRemoval.clear();
2284 }
2285
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002286 // If this transaction is part of a window animation then the next frame
2287 // we composite should be considered an animation as well.
2288 mAnimCompositionPending = mAnimTransactionPending;
2289
Mathias Agopian4fec8732012-06-29 14:12:52 -07002290 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002291 mDrawingState.traverseInZOrder([](Layer* layer) {
2292 layer->commitChildList();
2293 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002294 mTransactionPending = false;
2295 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002296 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002297}
2298
Robert Carr2047fae2016-11-28 14:09:09 -08002299void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002300 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002301{
Mathias Agopian841cde52012-03-01 15:44:37 -08002302 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002303 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002304
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002305 Region aboveOpaqueLayers;
2306 Region aboveCoveredLayers;
2307 Region dirty;
2308
Mathias Agopian87baae12012-07-31 12:38:26 -07002309 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002310
Robert Carr2047fae2016-11-28 14:09:09 -08002311 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002312 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002313 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002314
Jesse Hall01e29052013-02-19 16:13:35 -08002315 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002316 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002317 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002318
Mathias Agopianab028732010-03-16 16:41:46 -07002319 /*
2320 * opaqueRegion: area of a surface that is fully opaque.
2321 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002322 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002323
2324 /*
2325 * visibleRegion: area of a surface that is visible on screen
2326 * and not fully transparent. This is essentially the layer's
2327 * footprint minus the opaque regions above it.
2328 * Areas covered by a translucent surface are considered visible.
2329 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002330 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002331
2332 /*
2333 * coveredRegion: area of a surface that is covered by all
2334 * visible regions above it (which includes the translucent areas).
2335 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002336 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002337
Jesse Halla8026d22012-09-25 13:25:04 -07002338 /*
2339 * transparentRegion: area of a surface that is hinted to be completely
2340 * transparent. This is only used to tell when the layer has no visible
2341 * non-transparent regions and can be removed from the layer list. It
2342 * does not affect the visibleRegion of this layer or any layers
2343 * beneath it. The hint may not be correct if apps don't respect the
2344 * SurfaceView restrictions (which, sadly, some don't).
2345 */
2346 Region transparentRegion;
2347
Mathias Agopianab028732010-03-16 16:41:46 -07002348
2349 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002350 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002351 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002352 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002353 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002354 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002355 if (!visibleRegion.isEmpty()) {
2356 // Remove the transparent area from the visible region
2357 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002358 if (tr.preserveRects()) {
2359 // transform the transparent region
2360 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002361 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002362 // transformation too complex, can't do the
2363 // transparent region optimization.
2364 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002365 }
Mathias Agopianab028732010-03-16 16:41:46 -07002366 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367
Mathias Agopianab028732010-03-16 16:41:46 -07002368 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002369 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002370 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002371 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2372 // the opaque region is the layer's footprint
2373 opaqueRegion = visibleRegion;
2374 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002375 }
2376 }
2377
Mathias Agopianab028732010-03-16 16:41:46 -07002378 // Clip the covered region to the visible region
2379 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2380
2381 // Update aboveCoveredLayers for next (lower) layer
2382 aboveCoveredLayers.orSelf(visibleRegion);
2383
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384 // subtract the opaque region covered by the layers above us
2385 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002386
2387 // compute this layer's dirty region
2388 if (layer->contentDirty) {
2389 // we need to invalidate the whole region
2390 dirty = visibleRegion;
2391 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002392 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002393 layer->contentDirty = false;
2394 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002395 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002396 * the exposed region consists of two components:
2397 * 1) what's VISIBLE now and was COVERED before
2398 * 2) what's EXPOSED now less what was EXPOSED before
2399 *
2400 * note that (1) is conservative, we start with the whole
2401 * visible region but only keep what used to be covered by
2402 * something -- which mean it may have been exposed.
2403 *
2404 * (2) handles areas that were not covered by anything but got
2405 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002406 */
Mathias Agopianab028732010-03-16 16:41:46 -07002407 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002408 const Region oldVisibleRegion = layer->visibleRegion;
2409 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002410 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2411 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002412 }
2413 dirty.subtractSelf(aboveOpaqueLayers);
2414
2415 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002416 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002417
Mathias Agopianab028732010-03-16 16:41:46 -07002418 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002419 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002420
Jesse Halla8026d22012-09-25 13:25:04 -07002421 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002422 layer->setVisibleRegion(visibleRegion);
2423 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002424 layer->setVisibleNonTransparentRegion(
2425 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002426 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002427
Mathias Agopian87baae12012-07-31 12:38:26 -07002428 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002429}
2430
Mathias Agopian87baae12012-07-31 12:38:26 -07002431void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2432 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002433 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002434 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2435 if (hw->getLayerStack() == layerStack) {
2436 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002437 }
2438 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002439}
2440
Dan Stoza6b9454d2014-11-07 16:00:59 -08002441bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002442{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002443 ALOGV("handlePageFlip");
2444
Brian Andersond6927fb2016-07-23 23:37:30 -07002445 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002446
Mathias Agopian4fec8732012-06-29 14:12:52 -07002447 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002448 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002449 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002450
2451 // Store the set of layers that need updates. This set must not change as
2452 // buffers are being latched, as this could result in a deadlock.
2453 // Example: Two producers share the same command stream and:
2454 // 1.) Layer 0 is latched
2455 // 2.) Layer 0 gets a new frame
2456 // 2.) Layer 1 gets a new frame
2457 // 3.) Layer 1 is latched.
2458 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2459 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002460 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002461 if (layer->hasQueuedFrame()) {
2462 frameQueued = true;
2463 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002464 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002465 } else {
2466 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002467 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002468 } else {
2469 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002470 }
Robert Carr2047fae2016-11-28 14:09:09 -08002471 });
2472
Dan Stoza9e56aa02015-11-02 13:00:03 -08002473 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002474 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002475 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002476 invalidateLayerStack(layer->getLayerStack(), dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002477 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002478 newDataLatched = true;
2479 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002480 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002481
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002482 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002483
2484 // If we will need to wake up at some time in the future to deal with a
2485 // queued frame that shouldn't be displayed during this vsync period, wake
2486 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002487 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002488 signalLayerUpdate();
2489 }
2490
2491 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002492 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002493}
2494
Mathias Agopianad456f92011-01-13 17:53:01 -08002495void SurfaceFlinger::invalidateHwcGeometry()
2496{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002497 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002498}
2499
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002500
Fabien Sanglard830b8472016-11-30 16:35:58 -08002501void SurfaceFlinger::doDisplayComposition(
2502 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002503 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504{
Dan Stoza71433162014-02-04 16:22:36 -08002505 // We only need to actually compose the display if:
2506 // 1) It is being handled by hardware composer, which may need this to
2507 // keep its virtual display state machine in sync, or
2508 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002509 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002510 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002511 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002512 return;
2513 }
2514
Dan Stoza9e56aa02015-11-02 13:00:03 -08002515 ALOGV("doDisplayComposition");
2516
Mathias Agopian87baae12012-07-31 12:38:26 -07002517 Region dirtyRegion(inDirtyRegion);
2518
Mathias Agopianb8a55602009-06-26 19:06:36 -07002519 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002520 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002521
Fabien Sanglard830b8472016-11-30 16:35:58 -08002522 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002523 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002524 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2525 // takes a rectangle, we must make sure to update that whole
2526 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002527 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002528 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002529 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002530 // We need to redraw the rectangle that will be updated
2531 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002532 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002533 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002534 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002535 } else {
2536 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002537 dirtyRegion.set(displayDevice->bounds());
2538 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539 }
2540 }
2541
Fabien Sanglard830b8472016-11-30 16:35:58 -08002542 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002544 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002545 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002546
2547 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002548 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549}
2550
Dan Stoza9e56aa02015-11-02 13:00:03 -08002551bool SurfaceFlinger::doComposeSurfaces(
2552 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002553{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002554 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002555
Dan Stoza9e56aa02015-11-02 13:00:03 -08002556 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002557
2558 mat4 oldColorMatrix;
2559 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2560 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2561 if (applyColorMatrix) {
2562 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2563 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2564 }
2565
Dan Stoza9e56aa02015-11-02 13:00:03 -08002566 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2567 if (hasClientComposition) {
2568 ALOGV("hasClientComposition");
2569
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002570#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002571 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002572 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002573#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002574 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002575 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002576 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002577 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002578
2579 // |mStateLock| not needed as we are on the main thread
2580 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002581 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2582 }
2583 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002584 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002585
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002586 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002587 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2588 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002589 // when using overlays, we assume a fully transparent framebuffer
2590 // NOTE: we could reduce how much we need to clear, for instance
2591 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002592 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002593 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002594 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002595 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002596 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002597 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002598
2599 // we remove the scissor part
2600 // we're left with the letterbox region
2601 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002602 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002603
2604 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002606
2607 // but limit it to the dirty region
2608 region.andSelf(dirty);
2609
Mathias Agopianb9494d52012-04-18 02:28:45 -07002610 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002611 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002612 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002613 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002614 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002615 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002616
Dan Stoza9e56aa02015-11-02 13:00:03 -08002617 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002618 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002619 // scissor on the main display. It should never be needed
2620 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002621 const Rect& bounds(displayDevice->getBounds());
2622 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002623 if (scissor != bounds) {
2624 // scissor doesn't match the screen's dimensions, so we
2625 // need to clear everything outside of it and enable
2626 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002627
Mathias Agopianf45c5102012-10-24 16:29:17 -07002628 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002629 const uint32_t height = displayDevice->getHeight();
2630 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002631 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002632 }
2633 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002634 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002635
Mathias Agopian85d751c2012-08-29 16:59:24 -07002636 /*
2637 * and then, render the layers targeted at the framebuffer
2638 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002639
Dan Stoza9e56aa02015-11-02 13:00:03 -08002640 ALOGV("Rendering client layers");
2641 const Transform& displayTransform = displayDevice->getTransform();
2642 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002643 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002644 bool firstLayer = true;
2645 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2646 const Region clip(dirty.intersect(
2647 displayTransform.transform(layer->visibleRegion)));
2648 ALOGV("Layer: %s", layer->getName().string());
2649 ALOGV(" Composition type: %s",
2650 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002651 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002652 switch (layer->getCompositionType(hwcId)) {
2653 case HWC2::Composition::Cursor:
2654 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002655 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002656 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002657 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002658 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2659 layer->isOpaque(state) && (state.alpha == 1.0f)
2660 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002661 // never clear the very first layer since we're
2662 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002663 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002664 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002665 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002666 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002667 case HWC2::Composition::Client: {
2668 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002669 break;
2670 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002672 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002673 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002674 } else {
2675 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002676 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002677 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002678 }
2679 } else {
2680 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002681 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002682 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002683 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002684 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002685 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002686 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002687 }
2688 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002689
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002690 if (applyColorMatrix) {
2691 getRenderEngine().setupColorTransform(oldColorMatrix);
2692 }
2693
Mathias Agopianf45c5102012-10-24 16:29:17 -07002694 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002695 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002696 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002697}
2698
Fabien Sanglard830b8472016-11-30 16:35:58 -08002699void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2700 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002701 RenderEngine& engine(getRenderEngine());
2702 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002703}
2704
Dan Stoza7d89d062015-04-30 13:29:25 -07002705status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002706 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002707 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002708 const sp<Layer>& lbc,
2709 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002710{
Dan Stoza7d89d062015-04-30 13:29:25 -07002711 // add this layer to the current state list
2712 {
2713 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002714 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002715 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2716 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002717 return NO_MEMORY;
2718 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002719 if (parent == nullptr) {
2720 mCurrentState.layersSortedByZ.add(lbc);
2721 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002722 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2723 ALOGE("addClientLayer called with a removed parent");
2724 return NAME_NOT_FOUND;
2725 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002726 parent->addChild(lbc);
2727 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002728
Dan Stoza7d89d062015-04-30 13:29:25 -07002729 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002730 mLayersAdded = true;
2731 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002732 }
2733
Mathias Agopian96f08192010-06-02 23:28:45 -07002734 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002735 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002736
Dan Stoza7d89d062015-04-30 13:29:25 -07002737 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002738}
2739
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002740status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002741 Mutex::Autolock _l(mStateLock);
2742
Robert Carr1f0a16a2016-10-24 16:27:39 -07002743 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002744 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002745 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002746 if (topLevelOnly) {
2747 return NO_ERROR;
2748 }
2749
Chia-I Wu98f1c102017-05-30 14:54:08 -07002750 sp<Layer> ancestor = p;
2751 while (ancestor->getParent() != nullptr) {
2752 ancestor = ancestor->getParent();
2753 }
2754 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2755 ALOGE("removeLayer called with a layer whose parent has been removed");
2756 return NAME_NOT_FOUND;
2757 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002758
2759 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002760 } else {
2761 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002762 }
2763
Robert Carr136e2f62017-02-08 17:54:29 -08002764 // As a matter of normal operation, the LayerCleaner will produce a second
2765 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2766 // so we will succeed in promoting it, but it's already been removed
2767 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2768 // otherwise something has gone wrong and we are leaking the layer.
2769 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002770 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2771 layer->getName().string(),
2772 (p != nullptr) ? p->getName().string() : "no-parent");
2773 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002774 } else if (index < 0) {
2775 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002776 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002777
2778 mLayersPendingRemoval.add(layer);
2779 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002780 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002781 setTransactionFlags(eTransactionNeeded);
2782 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783}
2784
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002785uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002786 return android_atomic_release_load(&mTransactionFlags);
2787}
2788
Mathias Agopian3f844832013-08-07 21:24:32 -07002789uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2791}
2792
Mathias Agopian3f844832013-08-07 21:24:32 -07002793uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2795 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002796 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797 }
2798 return old;
2799}
2800
Mathias Agopian8b33f032012-07-24 20:43:54 -07002801void SurfaceFlinger::setTransactionState(
2802 const Vector<ComposerState>& state,
2803 const Vector<DisplayState>& displays,
2804 uint32_t flags)
2805{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002806 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002807 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002808 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002809
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002810 if (flags & eAnimation) {
2811 // For window updates that are part of an animation we must wait for
2812 // previous animation "frames" to be handled.
2813 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002814 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002815 if (CC_UNLIKELY(err != NO_ERROR)) {
2816 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002817 // caller after a few seconds.
2818 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2819 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002820 mAnimTransactionPending = false;
2821 break;
2822 }
2823 }
2824 }
2825
Mathias Agopiane57f2922012-08-09 16:29:12 -07002826 size_t count = displays.size();
2827 for (size_t i=0 ; i<count ; i++) {
2828 const DisplayState& s(displays[i]);
2829 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002830 }
2831
Mathias Agopiane57f2922012-08-09 16:29:12 -07002832 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002833 for (size_t i=0 ; i<count ; i++) {
2834 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002835 // Here we need to check that the interface we're given is indeed
2836 // one of our own. A malicious client could give us a NULL
2837 // IInterface, or one of its own or even one of our own but a
2838 // different type. All these situations would cause us to crash.
2839 //
2840 // NOTE: it would be better to use RTTI as we could directly check
2841 // that we have a Client*. however, RTTI is disabled in Android.
2842 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002843 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002844 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002845 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002846 sp<Client> client( static_cast<Client *>(s.client.get()) );
2847 transactionFlags |= setClientStateLocked(client, s.state);
2848 }
2849 }
2850 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002851 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002852
Robert Carr2a7dbb42016-05-24 11:41:28 -07002853 // If a synchronous transaction is explicitly requested without any changes,
2854 // force a transaction anyway. This can be used as a flush mechanism for
2855 // previous async transactions.
2856 if (transactionFlags == 0 && (flags & eSynchronous)) {
2857 transactionFlags = eTransactionNeeded;
2858 }
2859
Mathias Agopian386aa982011-11-07 21:58:03 -08002860 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002861 if (mInterceptor.isEnabled()) {
2862 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2863 }
Irvel468051e2016-06-13 16:44:44 -07002864
Mathias Agopian386aa982011-11-07 21:58:03 -08002865 // this triggers the transaction
2866 setTransactionFlags(transactionFlags);
2867
2868 // if this is a synchronous transaction, wait for it to take effect
2869 // before returning.
2870 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002871 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002872 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002873 if (flags & eAnimation) {
2874 mAnimTransactionPending = true;
2875 }
2876 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002877 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2878 if (CC_UNLIKELY(err != NO_ERROR)) {
2879 // just in case something goes wrong in SF, return to the
2880 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002881 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2882 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002883 break;
2884 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002885 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886 }
2887}
2888
Mathias Agopiane57f2922012-08-09 16:29:12 -07002889uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2890{
Jesse Hall9a143922012-10-04 16:29:19 -07002891 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2892 if (dpyIdx < 0)
2893 return 0;
2894
Mathias Agopiane57f2922012-08-09 16:29:12 -07002895 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002896 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002897 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002898 const uint32_t what = s.what;
2899 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002900 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002901 disp.surface = s.surface;
2902 flags |= eDisplayTransactionNeeded;
2903 }
2904 }
2905 if (what & DisplayState::eLayerStackChanged) {
2906 if (disp.layerStack != s.layerStack) {
2907 disp.layerStack = s.layerStack;
2908 flags |= eDisplayTransactionNeeded;
2909 }
2910 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002911 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002912 if (disp.orientation != s.orientation) {
2913 disp.orientation = s.orientation;
2914 flags |= eDisplayTransactionNeeded;
2915 }
2916 if (disp.frame != s.frame) {
2917 disp.frame = s.frame;
2918 flags |= eDisplayTransactionNeeded;
2919 }
2920 if (disp.viewport != s.viewport) {
2921 disp.viewport = s.viewport;
2922 flags |= eDisplayTransactionNeeded;
2923 }
2924 }
Michael Lentine47e45402014-07-18 15:34:25 -07002925 if (what & DisplayState::eDisplaySizeChanged) {
2926 if (disp.width != s.width) {
2927 disp.width = s.width;
2928 flags |= eDisplayTransactionNeeded;
2929 }
2930 if (disp.height != s.height) {
2931 disp.height = s.height;
2932 flags |= eDisplayTransactionNeeded;
2933 }
2934 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002935 }
2936 return flags;
2937}
2938
2939uint32_t SurfaceFlinger::setClientStateLocked(
2940 const sp<Client>& client,
2941 const layer_state_t& s)
2942{
2943 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002944 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002945 if (layer != 0) {
2946 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002947 bool geometryAppliesWithResize =
2948 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002949 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002950 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002951 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002952 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002953 }
2954 if (what & layer_state_t::eLayerChanged) {
2955 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002956 const auto& p = layer->getParent();
2957 if (p == nullptr) {
2958 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2959 if (layer->setLayer(s.z) && idx >= 0) {
2960 mCurrentState.layersSortedByZ.removeAt(idx);
2961 mCurrentState.layersSortedByZ.add(layer);
2962 // we need traversal (state changed)
2963 // AND transaction (list changed)
2964 flags |= eTransactionNeeded|eTraversalNeeded;
2965 }
2966 } else {
2967 if (p->setChildLayer(layer, s.z)) {
2968 flags |= eTransactionNeeded|eTraversalNeeded;
2969 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002970 }
2971 }
Robert Carrdb66e622017-04-10 16:55:57 -07002972 if (what & layer_state_t::eRelativeLayerChanged) {
2973 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2974 flags |= eTransactionNeeded|eTraversalNeeded;
2975 }
2976 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002977 if (what & layer_state_t::eSizeChanged) {
2978 if (layer->setSize(s.w, s.h)) {
2979 flags |= eTraversalNeeded;
2980 }
2981 }
2982 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002983 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002984 flags |= eTraversalNeeded;
2985 }
2986 if (what & layer_state_t::eMatrixChanged) {
2987 if (layer->setMatrix(s.matrix))
2988 flags |= eTraversalNeeded;
2989 }
2990 if (what & layer_state_t::eTransparentRegionChanged) {
2991 if (layer->setTransparentRegionHint(s.transparentRegion))
2992 flags |= eTraversalNeeded;
2993 }
Dan Stoza23116082015-06-18 14:58:39 -07002994 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002995 if (layer->setFlags(s.flags, s.mask))
2996 flags |= eTraversalNeeded;
2997 }
2998 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002999 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003000 flags |= eTraversalNeeded;
3001 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003002 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003003 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003004 flags |= eTraversalNeeded;
3005 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003006 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003007 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003008 // We only allow setting layer stacks for top level layers,
3009 // everything else inherits layer stack from its parent.
3010 if (layer->hasParent()) {
3011 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3012 layer->getName().string());
3013 } else if (idx < 0) {
3014 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3015 "that also does not appear in the top level layer list. Something"
3016 " has gone wrong.", layer->getName().string());
3017 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003018 mCurrentState.layersSortedByZ.removeAt(idx);
3019 mCurrentState.layersSortedByZ.add(layer);
3020 // we need traversal (state changed)
3021 // AND transaction (list changed)
3022 flags |= eTransactionNeeded|eTraversalNeeded;
3023 }
3024 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003025 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003026 if (s.barrierHandle != nullptr) {
3027 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3028 } else if (s.barrierGbp != nullptr) {
3029 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3030 if (authenticateSurfaceTextureLocked(gbp)) {
3031 const auto& otherLayer =
3032 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3033 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3034 } else {
3035 ALOGE("Attempt to defer transaction to to an"
3036 " unrecognized GraphicBufferProducer");
3037 }
3038 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003039 // We don't trigger a traversal here because if no other state is
3040 // changed, we don't want this to cause any more work
3041 }
Robert Carr1db73f62016-12-21 12:58:51 -08003042 if (what & layer_state_t::eReparentChildren) {
3043 if (layer->reparentChildren(s.reparentHandle)) {
3044 flags |= eTransactionNeeded|eTraversalNeeded;
3045 }
3046 }
Robert Carr9524cb32017-02-13 11:32:32 -08003047 if (what & layer_state_t::eDetachChildren) {
3048 layer->detachChildren();
3049 }
Robert Carrc3574f72016-03-24 12:19:32 -07003050 if (what & layer_state_t::eOverrideScalingModeChanged) {
3051 layer->setOverrideScalingMode(s.overrideScalingMode);
3052 // We don't trigger a traversal here because if no other state is
3053 // changed, we don't want this to cause any more work
3054 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003055 }
3056 return flags;
3057}
3058
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003059status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003060 const String8& name,
3061 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003062 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003063 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3064 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003065{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003066 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003067 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003068 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003069 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003070 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003071
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003072 status_t result = NO_ERROR;
3073
3074 sp<Layer> layer;
3075
Cody Northropbc755282017-03-31 12:00:08 -06003076 String8 uniqueName = getUniqueLayerName(name);
3077
Mathias Agopian3165cc22012-08-08 19:42:09 -07003078 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3079 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003080 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003081 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003082 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003084 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003085 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003086 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003087 handle, gbp, &layer);
3088 break;
3089 default:
3090 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091 break;
3092 }
3093
Dan Stoza7d89d062015-04-30 13:29:25 -07003094 if (result != NO_ERROR) {
3095 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003097
Albert Chaulk479c60c2017-01-27 14:21:34 -05003098 layer->setInfo(windowType, ownerUid);
3099
Robert Carr1f0a16a2016-10-24 16:27:39 -07003100 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003101 if (result != NO_ERROR) {
3102 return result;
3103 }
Irvelffc9efc2016-07-27 15:16:37 -07003104 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003105
3106 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003107 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003108}
3109
Cody Northropbc755282017-03-31 12:00:08 -06003110String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3111{
3112 bool matchFound = true;
3113 uint32_t dupeCounter = 0;
3114
3115 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3116 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3117
3118 // Loop over layers until we're sure there is no matching name
3119 while (matchFound) {
3120 matchFound = false;
3121 mDrawingState.traverseInZOrder([&](Layer* layer) {
3122 if (layer->getName() == uniqueName) {
3123 matchFound = true;
3124 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3125 }
3126 });
3127 }
3128
3129 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3130
3131 return uniqueName;
3132}
3133
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003134status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3135 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3136 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137{
3138 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003139 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140 case PIXEL_FORMAT_TRANSPARENT:
3141 case PIXEL_FORMAT_TRANSLUCENT:
3142 format = PIXEL_FORMAT_RGBA_8888;
3143 break;
3144 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003145 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146 break;
3147 }
3148
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003149 *outLayer = new Layer(this, client, name, w, h, flags);
3150 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3151 if (err == NO_ERROR) {
3152 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003153 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003155
3156 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3157 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158}
3159
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003160status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3161 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3162 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003164 *outLayer = new LayerDim(this, client, name, w, h, flags);
3165 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003166 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003167 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003168}
3169
Mathias Agopianac9fa422013-02-11 16:40:36 -08003170status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171{
Robert Carr9524cb32017-02-13 11:32:32 -08003172 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003173 status_t err = NO_ERROR;
3174 sp<Layer> l(client->getLayerUser(handle));
3175 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003176 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003177 err = removeLayer(l);
3178 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3179 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003180 }
3181 return err;
3182}
3183
Mathias Agopian13127d82013-03-05 17:47:11 -08003184status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003185{
Mathias Agopian67106042013-03-14 19:18:13 -07003186 // called by ~LayerCleaner() when all references to the IBinder (handle)
3187 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003188 sp<Layer> l = layer.promote();
3189 if (l == nullptr) {
3190 // The layer has already been removed, carry on
3191 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003192 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003193 // If we have a parent, then we can continue to live as long as it does.
3194 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195}
3196
Mathias Agopianb60314a2012-04-10 22:09:54 -07003197// ---------------------------------------------------------------------------
3198
Andy McFadden13a082e2012-08-24 10:16:42 -07003199void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003200 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003201 Vector<ComposerState> state;
3202 Vector<DisplayState> displays;
3203 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003204 d.what = DisplayState::eDisplayProjectionChanged |
3205 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003206 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003207 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003208 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003209 d.frame.makeInvalid();
3210 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003211 d.width = 0;
3212 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003213 displays.add(d);
3214 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003215 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003216
Dan Stoza9e56aa02015-11-02 13:00:03 -08003217 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3218 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003219 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003220
Brian Andersond0010582017-03-07 13:20:31 -08003221 // Use phase of 0 since phase is not known.
3222 // Use latency of 0, which will snap to the ideal latency.
3223 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003224}
3225
3226void SurfaceFlinger::initializeDisplays() {
3227 class MessageScreenInitialized : public MessageBase {
3228 SurfaceFlinger* flinger;
3229 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003230 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003231 virtual bool handler() {
3232 flinger->onInitializeDisplays();
3233 return true;
3234 }
3235 };
3236 sp<MessageBase> msg = new MessageScreenInitialized(this);
3237 postMessageAsync(msg); // we may be called from main thread, use async message
3238}
3239
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003240void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3241 int mode) {
3242 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3243 this);
3244 int32_t type = hw->getDisplayType();
3245 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003246
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003247 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003248 return;
3249 }
3250
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003251 hw->setPowerMode(mode);
3252 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3253 ALOGW("Trying to set power mode for virtual display");
3254 return;
3255 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003256
Irvelffc9efc2016-07-27 15:16:37 -07003257 if (mInterceptor.isEnabled()) {
3258 Mutex::Autolock _l(mStateLock);
3259 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3260 if (idx < 0) {
3261 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3262 return;
3263 }
3264 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3265 }
3266
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003267 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003268 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003269 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003270 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3271 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003272 // FIXME: eventthread only knows about the main display right now
3273 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003274 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003276
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003277 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003278 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003279 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003280
3281 struct sched_param param = {0};
3282 param.sched_priority = 1;
3283 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3284 ALOGW("Couldn't set SCHED_FIFO on display on");
3285 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003286 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003287 // Turn off the display
3288 struct sched_param param = {0};
3289 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3290 ALOGW("Couldn't set SCHED_OTHER on display off");
3291 }
3292
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003293 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003294 disableHardwareVsync(true); // also cancels any in-progress resync
3295
Mathias Agopiancde87a32012-09-13 14:09:01 -07003296 // FIXME: eventthread only knows about the main display right now
3297 mEventThread->onScreenReleased();
3298 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003299
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003300 getHwComposer().setPowerMode(type, mode);
3301 mVisibleRegionsDirty = true;
3302 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003303 } else if (mode == HWC_POWER_MODE_DOZE ||
3304 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003305 // Update display while dozing
3306 getHwComposer().setPowerMode(type, mode);
3307 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3308 // FIXME: eventthread only knows about the main display right now
3309 mEventThread->onScreenAcquired();
3310 resyncToHardwareVsync(true);
3311 }
3312 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3313 // Leave display going to doze
3314 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3315 disableHardwareVsync(true); // also cancels any in-progress resync
3316 // FIXME: eventthread only knows about the main display right now
3317 mEventThread->onScreenReleased();
3318 }
3319 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003320 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003321 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003322 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003323 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003324}
3325
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003326void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3327 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003328 SurfaceFlinger& mFlinger;
3329 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003330 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003331 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003332 MessageSetPowerMode(SurfaceFlinger& flinger,
3333 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3334 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003335 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003336 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003337 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003338 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003339 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003340 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003341 ALOGW("Attempt to set power mode = %d for virtual display",
3342 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003343 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003344 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003345 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003346 return true;
3347 }
3348 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003349 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003350 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003351}
3352
3353// ---------------------------------------------------------------------------
3354
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003355status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3356{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003357 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003358
Mathias Agopianbd115332013-04-18 16:41:04 -07003359 IPCThreadState* ipc = IPCThreadState::self();
3360 const int pid = ipc->getCallingPid();
3361 const int uid = ipc->getCallingUid();
3362 if ((uid != AID_SHELL) &&
3363 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003364 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003365 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003367 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003368 // (this would indicate SF is stuck, but we want to be able to
3369 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003370 status_t err = mStateLock.timedLock(s2ns(1));
3371 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003372 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003373 result.appendFormat(
3374 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3375 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003376 }
3377
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003378 bool dumpAll = true;
3379 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003380 size_t numArgs = args.size();
3381 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003382 if ((index < numArgs) &&
3383 (args[index] == String16("--list"))) {
3384 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003385 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003386 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003387 }
3388
3389 if ((index < numArgs) &&
3390 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003391 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003392 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003393 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003394 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003395
3396 if ((index < numArgs) &&
3397 (args[index] == String16("--latency-clear"))) {
3398 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003399 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003400 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003401 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003402
3403 if ((index < numArgs) &&
3404 (args[index] == String16("--dispsync"))) {
3405 index++;
3406 mPrimaryDispSync.dump(result);
3407 dumpAll = false;
3408 }
Dan Stozab90cf072015-03-05 11:05:59 -08003409
3410 if ((index < numArgs) &&
3411 (args[index] == String16("--static-screen"))) {
3412 index++;
3413 dumpStaticScreenStats(result);
3414 dumpAll = false;
3415 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003416
3417 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003418 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003419 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003420 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003421 dumpAll = false;
3422 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003423
3424 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3425 index++;
3426 dumpWideColorInfo(result);
3427 dumpAll = false;
3428 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003429 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003430
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003431 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003432 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003433 }
3434
Mathias Agopian9795c422009-08-26 16:36:26 -07003435 if (locked) {
3436 mStateLock.unlock();
3437 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003438 }
3439 write(fd, result.string(), result.size());
3440 return NO_ERROR;
3441}
3442
Dan Stozac7014012014-02-14 15:03:43 -08003443void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3444 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003445{
Robert Carr2047fae2016-11-28 14:09:09 -08003446 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003447 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003448 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003449}
3450
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003451void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003452 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003453{
3454 String8 name;
3455 if (index < args.size()) {
3456 name = String8(args[index]);
3457 index++;
3458 }
3459
Dan Stoza9e56aa02015-11-02 13:00:03 -08003460 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3461 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003462 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003463
3464 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003465 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003466 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003467 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003468 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003469 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003470 }
Robert Carr2047fae2016-11-28 14:09:09 -08003471 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003472 }
3473}
3474
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003475void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003476 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003477{
3478 String8 name;
3479 if (index < args.size()) {
3480 name = String8(args[index]);
3481 index++;
3482 }
3483
Robert Carr2047fae2016-11-28 14:09:09 -08003484 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003485 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003486 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003487 }
Robert Carr2047fae2016-11-28 14:09:09 -08003488 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003489
Svetoslavd85084b2014-03-20 10:28:31 -07003490 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003491}
3492
Jamie Gennis6547ff42013-07-16 20:12:42 -07003493// This should only be called from the main thread. Otherwise it would need
3494// the lock and should use mCurrentState rather than mDrawingState.
3495void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003496 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003497 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003498 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003499
3500 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3501}
3502
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003503void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003504{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003505 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003506 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3507
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003508 if (isLayerTripleBufferingDisabled())
3509 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003510
3511 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003512 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003513 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003514 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003515 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3516 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003517 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003518}
3519
Dan Stozab90cf072015-03-05 11:05:59 -08003520void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3521{
3522 result.appendFormat("Static screen stats:\n");
3523 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3524 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3525 float percent = 100.0f *
3526 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3527 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3528 b + 1, bucketTimeSec, percent);
3529 }
3530 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3531 float percent = 100.0f *
3532 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3533 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3534 NUM_BUCKETS - 1, bucketTimeSec, percent);
3535}
3536
Dan Stozae77c7662016-05-13 11:37:28 -07003537void SurfaceFlinger::recordBufferingStats(const char* layerName,
3538 std::vector<OccupancyTracker::Segment>&& history) {
3539 Mutex::Autolock lock(mBufferingStatsMutex);
3540 auto& stats = mBufferingStats[layerName];
3541 for (const auto& segment : history) {
3542 if (!segment.usedThirdBuffer) {
3543 stats.twoBufferTime += segment.totalTime;
3544 }
3545 if (segment.occupancyAverage < 1.0f) {
3546 stats.doubleBufferedTime += segment.totalTime;
3547 } else if (segment.occupancyAverage < 2.0f) {
3548 stats.tripleBufferedTime += segment.totalTime;
3549 }
3550 ++stats.numSegments;
3551 stats.totalTime += segment.totalTime;
3552 }
3553}
3554
Brian Andersond6927fb2016-07-23 23:37:30 -07003555void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3556 result.appendFormat("Layer frame timestamps:\n");
3557
3558 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3559 const size_t count = currentLayers.size();
3560 for (size_t i=0 ; i<count ; i++) {
3561 currentLayers[i]->dumpFrameEvents(result);
3562 }
3563}
3564
Dan Stozae77c7662016-05-13 11:37:28 -07003565void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3566 result.append("Buffering stats:\n");
3567 result.append(" [Layer name] <Active time> <Two buffer> "
3568 "<Double buffered> <Triple buffered>\n");
3569 Mutex::Autolock lock(mBufferingStatsMutex);
3570 typedef std::tuple<std::string, float, float, float> BufferTuple;
3571 std::map<float, BufferTuple, std::greater<float>> sorted;
3572 for (const auto& statsPair : mBufferingStats) {
3573 const char* name = statsPair.first.c_str();
3574 const BufferingStats& stats = statsPair.second;
3575 if (stats.numSegments == 0) {
3576 continue;
3577 }
3578 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3579 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3580 stats.totalTime;
3581 float doubleBufferRatio = static_cast<float>(
3582 stats.doubleBufferedTime) / stats.totalTime;
3583 float tripleBufferRatio = static_cast<float>(
3584 stats.tripleBufferedTime) / stats.totalTime;
3585 sorted.insert({activeTime, {name, twoBufferRatio,
3586 doubleBufferRatio, tripleBufferRatio}});
3587 }
3588 for (const auto& sortedPair : sorted) {
3589 float activeTime = sortedPair.first;
3590 const BufferTuple& values = sortedPair.second;
3591 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3592 std::get<0>(values).c_str(), activeTime,
3593 std::get<1>(values), std::get<2>(values),
3594 std::get<3>(values));
3595 }
3596 result.append("\n");
3597}
3598
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003599void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3600 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3601
3602 // TODO: print out if wide-color mode is active or not
3603
3604 for (size_t d = 0; d < mDisplays.size(); d++) {
3605 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3606 int32_t hwcId = displayDevice->getHwcDisplayId();
3607 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3608 continue;
3609 }
3610
3611 result.appendFormat("Display %d color modes:\n", hwcId);
3612 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3613 for (auto&& mode : modes) {
3614 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3615 }
3616
3617 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3618 result.appendFormat(" Current color mode: %s (%d)\n",
3619 decodeColorMode(currentMode).c_str(), currentMode);
3620 }
3621 result.append("\n");
3622}
3623
Mathias Agopian74d211a2013-04-22 16:55:35 +02003624void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3625 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003626{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003627 bool colorize = false;
3628 if (index < args.size()
3629 && (args[index] == String16("--color"))) {
3630 colorize = true;
3631 index++;
3632 }
3633
3634 Colorizer colorizer(colorize);
3635
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003636 // figure out if we're stuck somewhere
3637 const nsecs_t now = systemTime();
3638 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3639 const nsecs_t inTransaction(mDebugInTransaction);
3640 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3641 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3642
3643 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003644 * Dump library configuration.
3645 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003646
3647 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003648 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003649 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003650 appendSfConfigString(result);
3651 appendUiConfigString(result);
3652 appendGuiConfigString(result);
3653 result.append("\n");
3654
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003655 result.append("\nWide-Color information:\n");
3656 dumpWideColorInfo(result);
3657
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003658 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003659 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003660 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003661 result.append(SyncFeatures::getInstance().toString());
3662 result.append("\n");
3663
Dan Stoza9e56aa02015-11-02 13:00:03 -08003664 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3665
Andy McFadden41d67d72014-04-25 16:58:34 -07003666 colorizer.bold(result);
3667 result.append("DispSync configuration: ");
3668 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003669 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003670 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003671 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003672 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003673 result.append("\n");
3674
Dan Stozab90cf072015-03-05 11:05:59 -08003675 // Dump static screen stats
3676 result.append("\n");
3677 dumpStaticScreenStats(result);
3678 result.append("\n");
3679
Dan Stozae77c7662016-05-13 11:37:28 -07003680 dumpBufferingStats(result);
3681
Andy McFadden4803b742012-09-24 19:07:20 -07003682 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003683 * Dump the visible layer list
3684 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003685 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003686 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003687 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003688 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003689 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003690 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003691
3692 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003693 * Dump Display state
3694 */
3695
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003696 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003697 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003698 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003699 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3700 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003701 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003702 }
3703
3704 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003705 * Dump SurfaceFlinger global state
3706 */
3707
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003708 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003709 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003710 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003711
Mathias Agopian888c8222012-08-04 21:10:38 -07003712 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003713 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003714
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003715 colorizer.bold(result);
3716 result.appendFormat("EGL implementation : %s\n",
3717 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3718 colorizer.reset(result);
3719 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003720 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003721
Mathias Agopian875d8e12013-06-07 15:35:48 -07003722 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003723
Mathias Agopian42977342012-08-05 00:40:46 -07003724 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003725 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3726 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003727 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003728 " last eglSwapBuffers() time: %f us\n"
3729 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003730 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003731 " refresh-rate : %f fps\n"
3732 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003733 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003734 " gpu_to_cpu_unsupported : %d\n"
3735 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003736 mLastSwapBufferTime/1000.0,
3737 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003738 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003739 1e9 / activeConfig->getVsyncPeriod(),
3740 activeConfig->getDpiX(),
3741 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003742 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003743
Mathias Agopian74d211a2013-04-22 16:55:35 +02003744 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003745 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003746
Mathias Agopian74d211a2013-04-22 16:55:35 +02003747 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003748 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003749
3750 /*
3751 * VSYNC state
3752 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003753 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003754 result.append("\n");
3755
3756 /*
3757 * HWC layer minidump
3758 */
3759 for (size_t d = 0; d < mDisplays.size(); d++) {
3760 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3761 int32_t hwcId = displayDevice->getHwcDisplayId();
3762 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3763 continue;
3764 }
3765
3766 result.appendFormat("Display %d HWC layers:\n", hwcId);
3767 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003768 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003769 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003770 });
Dan Stozae22aec72016-08-01 13:20:59 -07003771 result.append("\n");
3772 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003773
3774 /*
3775 * Dump HWComposer state
3776 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003777 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003778 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003779 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003780 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003781 result.appendFormat(" h/w composer %s\n",
3782 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003783 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003784
3785 /*
3786 * Dump gralloc state
3787 */
3788 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3789 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003790
3791 /*
3792 * Dump VrFlinger state if in use.
3793 */
3794 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3795 result.append("VrFlinger state:\n");
3796 result.append(mVrFlinger->Dump().c_str());
3797 result.append("\n");
3798 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003799}
3800
Mathias Agopian13127d82013-03-05 17:47:11 -08003801const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003802SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003803 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003804 wp<IBinder> dpy;
3805 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3806 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3807 dpy = mDisplays.keyAt(i);
3808 break;
3809 }
3810 }
3811 if (dpy == NULL) {
3812 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3813 // Just use the primary display so we have something to return
3814 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3815 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003816 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003817}
3818
Keun young Park63f165f2012-08-31 10:53:36 -07003819bool SurfaceFlinger::startDdmConnection()
3820{
3821 void* libddmconnection_dso =
3822 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3823 if (!libddmconnection_dso) {
3824 return false;
3825 }
3826 void (*DdmConnection_start)(const char* name);
3827 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003828 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003829 if (!DdmConnection_start) {
3830 dlclose(libddmconnection_dso);
3831 return false;
3832 }
3833 (*DdmConnection_start)(getServiceName());
3834 return true;
3835}
3836
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003837status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003838 switch (code) {
3839 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003840 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003841 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003842 case CLEAR_ANIMATION_FRAME_STATS:
3843 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003844 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003845 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003846 {
3847 // codes that require permission check
3848 IPCThreadState* ipc = IPCThreadState::self();
3849 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003850 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003851 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003852 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003853 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003854 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003855 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003856 break;
3857 }
Robert Carr1db73f62016-12-21 12:58:51 -08003858 /*
3859 * Calling setTransactionState is safe, because you need to have been
3860 * granted a reference to Client* and Handle* to do anything with it.
3861 *
3862 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3863 */
3864 case SET_TRANSACTION_STATE:
3865 case CREATE_SCOPED_CONNECTION:
3866 {
3867 return OK;
3868 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003869 case CAPTURE_SCREEN:
3870 {
3871 // codes that require permission check
3872 IPCThreadState* ipc = IPCThreadState::self();
3873 const int pid = ipc->getCallingPid();
3874 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003875 if ((uid != AID_GRAPHICS) &&
3876 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003877 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003878 return PERMISSION_DENIED;
3879 }
3880 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003881 }
3882 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003883 return OK;
3884}
3885
3886status_t SurfaceFlinger::onTransact(
3887 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3888{
3889 status_t credentialCheck = CheckTransactCodeCredentials(code);
3890 if (credentialCheck != OK) {
3891 return credentialCheck;
3892 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003893
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003894 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3895 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003896 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003897 IPCThreadState* ipc = IPCThreadState::self();
3898 const int uid = ipc->getCallingUid();
3899 if (CC_UNLIKELY(uid != AID_SYSTEM
3900 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003901 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003902 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003903 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003904 return PERMISSION_DENIED;
3905 }
3906 int n;
3907 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003908 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003909 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003910 return NO_ERROR;
3911 case 1002: // SHOW_UPDATES
3912 n = data.readInt32();
3913 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003914 invalidateHwcGeometry();
3915 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003916 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003917 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003918 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003919 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003920 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003921 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003922 setTransactionFlags(
3923 eTransactionNeeded|
3924 eDisplayTransactionNeeded|
3925 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003926 return NO_ERROR;
3927 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003928 case 1006:{ // send empty update
3929 signalRefresh();
3930 return NO_ERROR;
3931 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003932 case 1008: // toggle use of hw composer
3933 n = data.readInt32();
3934 mDebugDisableHWC = n ? 1 : 0;
3935 invalidateHwcGeometry();
3936 repaintEverything();
3937 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003938 case 1009: // toggle use of transform hint
3939 n = data.readInt32();
3940 mDebugDisableTransformHint = n ? 1 : 0;
3941 invalidateHwcGeometry();
3942 repaintEverything();
3943 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003944 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003945 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003946 reply->writeInt32(0);
3947 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003948 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003949 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003950 return NO_ERROR;
3951 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003952 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003953 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003954 return NO_ERROR;
3955 }
3956 case 1014: {
3957 // daltonize
3958 n = data.readInt32();
3959 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003960 case 1:
3961 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3962 break;
3963 case 2:
3964 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3965 break;
3966 case 3:
3967 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3968 break;
3969 default:
3970 mDaltonizer.setType(ColorBlindnessType::None);
3971 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003972 }
3973 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003974 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003975 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003976 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003977 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003978 invalidateHwcGeometry();
3979 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003980 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003981 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003982 case 1015: {
3983 // apply a color matrix
3984 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003985 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07003986 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07003987 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003988 for (size_t j = 0; j < 4; j++) {
3989 mColorMatrix[i][j] = data.readFloat();
3990 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003991 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003992 } else {
3993 mColorMatrix = mat4();
3994 }
Romain Guy88d37dd2017-05-26 17:57:05 -07003995
3996 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
3997 // the division by w in the fragment shader
3998 float4 lastRow(transpose(mColorMatrix)[3]);
3999 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4000 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4001 }
4002
Alan Viverette9c5a3332013-09-12 20:04:35 -07004003 invalidateHwcGeometry();
4004 repaintEverything();
4005 return NO_ERROR;
4006 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004007 // This is an experimental interface
4008 // Needs to be shifted to proper binder interface when we productize
4009 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004010 n = data.readInt32();
4011 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004012 return NO_ERROR;
4013 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004014 case 1017: {
4015 n = data.readInt32();
4016 mForceFullDamage = static_cast<bool>(n);
4017 return NO_ERROR;
4018 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004019 case 1018: { // Modify Choreographer's phase offset
4020 n = data.readInt32();
4021 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4022 return NO_ERROR;
4023 }
4024 case 1019: { // Modify SurfaceFlinger's phase offset
4025 n = data.readInt32();
4026 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4027 return NO_ERROR;
4028 }
Irvel468051e2016-06-13 16:44:44 -07004029 case 1020: { // Layer updates interceptor
4030 n = data.readInt32();
4031 if (n) {
4032 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004033 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004034 }
4035 else{
4036 ALOGV("Interceptor disabled");
4037 mInterceptor.disable();
4038 }
4039 return NO_ERROR;
4040 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004041 case 1021: { // Disable HWC virtual displays
4042 n = data.readInt32();
4043 mUseHwcVirtualDisplays = !n;
4044 return NO_ERROR;
4045 }
Romain Guy0147a172017-06-01 13:53:56 -07004046 case 1022: { // Set saturation boost
4047 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4048
4049 invalidateHwcGeometry();
4050 repaintEverything();
4051 return NO_ERROR;
4052 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004053 }
4054 }
4055 return err;
4056}
4057
Mathias Agopian53331da2011-08-22 21:44:41 -07004058void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004059 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004060 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004061}
4062
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004063// Checks that the requested width and height are valid and updates them to the display dimensions
4064// if they are set to 0
4065static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4066 Transform::orientation_flags rotation,
4067 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4068 // get screen geometry
4069 uint32_t displayWidth = displayDevice->getWidth();
4070 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004071
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004072 if (rotation & Transform::ROT_90) {
4073 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004074 }
4075
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004076 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4077 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4078 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4079 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004080 }
4081
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004082 if (*requestedWidth == 0) {
4083 *requestedWidth = displayWidth;
4084 }
4085 if (*requestedHeight == 0) {
4086 *requestedHeight = displayHeight;
4087 }
4088
4089 return NO_ERROR;
4090}
4091
4092// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4093class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004094public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004095 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4096 ~WindowDisconnector() {
4097 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004098 }
4099
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004100private:
4101 ANativeWindow* mWindow;
4102 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004103};
4104
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004105static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4106 uint32_t requestedHeight, bool hasWideColorDisplay,
4107 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4108 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4109 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4110
4111 int err = 0;
4112 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4113 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4114 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4115 err |= native_window_set_usage(window, usage);
4116
4117 if (hasWideColorDisplay) {
4118 err |= native_window_set_buffers_data_space(window,
4119 renderEngineUsesWideColor
4120 ? HAL_DATASPACE_DISPLAY_P3
4121 : HAL_DATASPACE_V0_SRGB);
4122 }
4123
4124 if (err != NO_ERROR) {
4125 return BAD_VALUE;
4126 }
4127
4128 /* TODO: Once we have the sync framework everywhere this can use
4129 * server-side waits on the fence that dequeueBuffer returns.
4130 */
4131 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4132 if (err != NO_ERROR) {
4133 return err;
4134 }
4135
4136 return NO_ERROR;
4137}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004138
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004139status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4140 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004141 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004142 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004143 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004144 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004145
4146 if (CC_UNLIKELY(display == 0))
4147 return BAD_VALUE;
4148
4149 if (CC_UNLIKELY(producer == 0))
4150 return BAD_VALUE;
4151
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004152 // if we have secure windows on this display, never allow the screen capture
4153 // unless the producer interface is local (i.e.: we can take a screenshot for
4154 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004155 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004156
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004157 // Convert to surfaceflinger's internal rotation type.
4158 Transform::orientation_flags rotationFlags;
4159 switch (rotation) {
4160 case ISurfaceComposer::eRotateNone:
4161 rotationFlags = Transform::ROT_0;
4162 break;
4163 case ISurfaceComposer::eRotate90:
4164 rotationFlags = Transform::ROT_90;
4165 break;
4166 case ISurfaceComposer::eRotate180:
4167 rotationFlags = Transform::ROT_180;
4168 break;
4169 case ISurfaceComposer::eRotate270:
4170 rotationFlags = Transform::ROT_270;
4171 break;
4172 default:
4173 rotationFlags = Transform::ROT_0;
4174 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4175 break;
4176 }
4177
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004178 { // Autolock scope
4179 Mutex::Autolock lock(mStateLock);
4180 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4181 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004182 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004183
4184 // create a surface (because we're a producer, and we need to
4185 // dequeue/queue a buffer)
4186 sp<Surface> surface = new Surface(producer, false);
4187
4188 // Put the screenshot Surface into async mode so that
4189 // Layer::headFenceHasSignaled will always return true and we'll latch the
4190 // first buffer regardless of whether or not its acquire fence has
4191 // signaled. This is needed to avoid a race condition in the rotation
4192 // animation. See b/30209608
4193 surface->setAsyncMode(true);
4194
4195 ANativeWindow* window = surface.get();
4196
4197 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4198 if (result != NO_ERROR) {
4199 return result;
4200 }
4201 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4202
4203 ANativeWindowBuffer* buffer = nullptr;
4204 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4205 getRenderEngine().usesWideColor(), &buffer);
4206 if (result != NO_ERROR) {
4207 return result;
4208 }
4209
4210 // This mutex protects syncFd and captureResult for communication of the return values from the
4211 // main thread back to this Binder thread
4212 std::mutex captureMutex;
4213 std::condition_variable captureCondition;
4214 std::unique_lock<std::mutex> captureLock(captureMutex);
4215 int syncFd = -1;
4216 std::optional<status_t> captureResult;
4217
4218 sp<LambdaMessage> message = new LambdaMessage([&]() {
4219 // If there is a refresh pending, bug out early and tell the binder thread to try again
4220 // after the refresh.
4221 if (mRefreshPending) {
4222 ATRACE_NAME("Skipping screenshot for now");
4223 std::unique_lock<std::mutex> captureLock(captureMutex);
4224 captureResult = std::make_optional<status_t>(EAGAIN);
4225 captureCondition.notify_one();
4226 return;
4227 }
4228
4229 status_t result = NO_ERROR;
4230 int fd = -1;
4231 {
4232 Mutex::Autolock _l(mStateLock);
4233 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4234 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4235 minLayerZ, maxLayerZ, useIdentityTransform,
4236 rotationFlags, isLocalScreenshot, &fd);
4237 }
4238
4239 {
4240 std::unique_lock<std::mutex> captureLock(captureMutex);
4241 syncFd = fd;
4242 captureResult = std::make_optional<status_t>(result);
4243 captureCondition.notify_one();
4244 }
4245 });
4246
4247 result = postMessageAsync(message);
4248 if (result == NO_ERROR) {
4249 captureCondition.wait(captureLock, [&]() { return captureResult; });
4250 while (*captureResult == EAGAIN) {
4251 captureResult.reset();
4252 result = postMessageAsync(message);
4253 if (result != NO_ERROR) {
4254 return result;
4255 }
4256 captureCondition.wait(captureLock, [&]() { return captureResult; });
4257 }
4258 result = *captureResult;
4259 }
4260
4261 if (result == NO_ERROR) {
4262 // queueBuffer takes ownership of syncFd
4263 result = window->queueBuffer(window, buffer, syncFd);
4264 }
4265
4266 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004267}
4268
Mathias Agopian180f10d2013-04-10 22:55:41 -07004269
4270void SurfaceFlinger::renderScreenImplLocked(
4271 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004272 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004273 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004274 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004275{
4276 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004277 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004278
4279 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004280 const int32_t hw_w = hw->getWidth();
4281 const int32_t hw_h = hw->getHeight();
4282 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004283 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004284
Dan Stozac1879002014-05-22 15:59:05 -07004285 // if a default or invalid sourceCrop is passed in, set reasonable values
4286 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4287 !sourceCrop.isValid()) {
4288 sourceCrop.setLeftTop(Point(0, 0));
4289 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4290 }
4291
4292 // ensure that sourceCrop is inside screen
4293 if (sourceCrop.left < 0) {
4294 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4295 }
Dan Stozabe31f442014-06-11 11:20:54 -07004296 if (sourceCrop.right > hw_w) {
4297 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004298 }
4299 if (sourceCrop.top < 0) {
4300 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4301 }
Dan Stozabe31f442014-06-11 11:20:54 -07004302 if (sourceCrop.bottom > hw_h) {
4303 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004304 }
4305
Romain Guy88d37dd2017-05-26 17:57:05 -07004306#ifdef USE_HWC2
4307 engine.setWideColor(hw->getWideColorSupport());
4308 engine.setColorMode(hw->getActiveColorMode());
4309#endif
4310
Mathias Agopian180f10d2013-04-10 22:55:41 -07004311 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004312 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004313
4314 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004315 engine.setViewportAndProjection(
4316 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004317 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004318
4319 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004320 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004321
Robert Carr1f0a16a2016-10-24 16:27:39 -07004322 // We loop through the first level of layers without traversing,
4323 // as we need to interpret min/max layer Z in the top level Z space.
4324 for (const auto& layer : mDrawingState.layersSortedByZ) {
4325 if (layer->getLayerStack() != hw->getLayerStack()) {
4326 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004327 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004328 const Layer::State& state(layer->getDrawingState());
4329 if (state.z < minLayerZ || state.z > maxLayerZ) {
4330 continue;
4331 }
Dan Stoza412903f2017-04-27 13:42:17 -07004332 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004333 if (!layer->isVisible()) {
4334 return;
4335 }
4336 if (filtering) layer->setFiltering(true);
4337 layer->draw(hw, useIdentityTransform);
4338 if (filtering) layer->setFiltering(false);
4339 });
4340 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004341
Mathias Agopian931bda12013-08-28 18:11:46 -07004342 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004343}
4344
Dan Stozaabcda352017-06-01 14:37:39 -07004345// A simple RAII class that holds an EGLImage and destroys it either:
4346// a) When the destroy() method is called
4347// b) When the object goes out of scope
4348class ImageHolder {
4349public:
4350 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4351 ~ImageHolder() { destroy(); }
4352
4353 void destroy() {
4354 if (mImage != EGL_NO_IMAGE_KHR) {
4355 eglDestroyImageKHR(mDisplay, mImage);
4356 mImage = EGL_NO_IMAGE_KHR;
4357 }
4358 }
4359
4360private:
4361 const EGLDisplay mDisplay;
4362 EGLImageKHR mImage;
4363};
4364
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004365status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4366 ANativeWindowBuffer* buffer, Rect sourceCrop,
4367 uint32_t reqWidth, uint32_t reqHeight,
4368 int32_t minLayerZ, int32_t maxLayerZ,
4369 bool useIdentityTransform,
4370 Transform::orientation_flags rotation,
4371 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004372 ATRACE_CALL();
4373
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004374 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004375 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004376 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004377 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4378 (state.z < minLayerZ || state.z > maxLayerZ)) {
4379 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004380 }
Dan Stoza412903f2017-04-27 13:42:17 -07004381 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004382 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4383 layer->isSecure());
4384 });
4385 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004386
4387 if (!isLocalScreenshot && secureLayerIsVisible) {
4388 ALOGW("FB is protected: PERMISSION_DENIED");
4389 return PERMISSION_DENIED;
4390 }
4391
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004392 int syncFd = -1;
4393 // create an EGLImage from the buffer so we can later
4394 // turn it into a texture
4395 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4396 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4397 if (image == EGL_NO_IMAGE_KHR) {
4398 return BAD_VALUE;
4399 }
4400
Dan Stozaabcda352017-06-01 14:37:39 -07004401 // This will automatically destroy the image if we return before calling its destroy method
4402 ImageHolder imageHolder(mEGLDisplay, image);
4403
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004404 // this binds the given EGLImage as a framebuffer for the
4405 // duration of this scope.
4406 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004407 if (imageBond.getStatus() != NO_ERROR) {
4408 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004409 return INVALID_OPERATION;
4410 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004411
Dan Stozaabcda352017-06-01 14:37:39 -07004412 // this will in fact render into our dequeued buffer
4413 // via an FBO, which means we didn't have to create
4414 // an EGLSurface and therefore we're not
4415 // dependent on the context's EGLConfig.
4416 renderScreenImplLocked(
4417 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4418 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004419
Dan Stozaabcda352017-06-01 14:37:39 -07004420 // Attempt to create a sync khr object that can produce a sync point. If that
4421 // isn't available, create a non-dupable sync object in the fallback path and
4422 // wait on it directly.
4423 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4424 if (!DEBUG_SCREENSHOTS) {
4425 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4426 // native fence fd will not be populated until flush() is done.
4427 getRenderEngine().flush();
4428 }
4429
4430 if (sync != EGL_NO_SYNC_KHR) {
4431 // get the sync fd
4432 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4433 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4434 ALOGW("captureScreen: failed to dup sync khr object");
4435 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004436 }
Dan Stozaabcda352017-06-01 14:37:39 -07004437 eglDestroySyncKHR(mEGLDisplay, sync);
4438 } else {
4439 // fallback path
4440 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004441 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004442 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4443 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4444 EGLint eglErr = eglGetError();
4445 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4446 ALOGW("captureScreen: fence wait timed out");
4447 } else {
4448 ALOGW_IF(eglErr != EGL_SUCCESS,
4449 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004450 }
4451 eglDestroySyncKHR(mEGLDisplay, sync);
4452 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004453 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004454 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004455 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004456 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004457
4458 if (DEBUG_SCREENSHOTS) {
4459 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4460 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4461 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4462 hw, minLayerZ, maxLayerZ);
4463 delete [] pixels;
4464 }
4465
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004466 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004467 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004468
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004469 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004470}
4471
Mathias Agopiand5556842013-09-19 17:08:37 -07004472void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004473 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004474 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004475 for (size_t y=0 ; y<h ; y++) {
4476 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4477 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004478 if (p[x] != 0xFF000000) return;
4479 }
4480 }
4481 ALOGE("*** we just took a black screenshot ***\n"
4482 "requested minz=%d, maxz=%d, layerStack=%d",
4483 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004484
Robert Carr2047fae2016-11-28 14:09:09 -08004485 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004486 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004487 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004488 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4489 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004490 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004491 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4492 layer->isVisible() ? '+' : '-',
4493 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004494 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004495 i++;
4496 });
4497 }
4498 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004499 }
4500}
4501
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004502// ---------------------------------------------------------------------------
4503
Dan Stoza412903f2017-04-27 13:42:17 -07004504void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4505 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004506}
4507
Dan Stoza412903f2017-04-27 13:42:17 -07004508void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4509 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004510}
4511
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004512}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004513
4514
4515#if defined(__gl_h_)
4516#error "don't include gl/gl.h in this file"
4517#endif
4518
4519#if defined(__gl2_h_)
4520#error "don't include gl2/gl2.h in this file"
4521#endif