blob: 0ae52098840b31188d75438ebff0e960f14fc0a7 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
31#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080040#include <dvr/vr_flinger.h>
41
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060042#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070044#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070045
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080068#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070069#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070071#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080072#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070074#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Mathias Agopiana4912602012-07-12 14:25:33 -070079#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070080#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070081#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Mathias Agopianff2ed702013-09-01 21:36:12 -070083#include "Effects/Daltonizer.h"
84
Mathias Agopian875d8e12013-06-07 15:35:48 -070085#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070087
Jiyong Park4b20c2e2017-01-14 19:45:11 +090088#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090089#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091#define DISPLAY_COUNT 1
92
Mathias Agopianfee2b462013-07-03 12:34:01 -070093/*
94 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
95 * black pixels.
96 */
97#define DEBUG_SCREENSHOTS false
98
Mathias Agopianca088332013-03-28 17:44:13 -070099EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700102
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107// ---------------------------------------------------------------------------
108
Mathias Agopian99b49842011-06-27 16:05:52 -0700109const String16 sHardwareTest("android.permission.HARDWARE_TEST");
110const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
111const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
112const String16 sDump("android.permission.DUMP");
113
114// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800115int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
116int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700117bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700118int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700119bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800120uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800121bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800122bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800123int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600124bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700127 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700129 mTransactionPending(false),
130 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700131 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700132 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700133 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800134 mHwc(nullptr),
135 mRealHwc(nullptr),
136 mVrHwc(nullptr),
137 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800139 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800141 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800142 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700144 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700145 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700146 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700147 mDebugInSwapBuffers(0),
148 mLastSwapBufferTime(0),
149 mDebugInTransaction(0),
150 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700151 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700152 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800153 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000154 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700155 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700156 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700157 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800158 mHasPoweredOff(false),
159 mFrameBuckets(),
160 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700161 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800162 mNumLayers(0),
163 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800164{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800165 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800166
167 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
168 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
169
170 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
171 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
172
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800173 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
174 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700176 useContextPriority = getBool< ISurfaceFlingerConfigs,
177 &ISurfaceFlingerConfigs::useContextPriority>(false);
178
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700179 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
180 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
181
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700182 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
183 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
184
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800185 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
186 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
187
Steven Thomas050b2c82017-03-06 11:45:16 -0800188 // Vr flinger is only enabled on Daydream ready devices.
189 useVrFlinger = getBool< ISurfaceFlingerConfigs,
190 &ISurfaceFlingerConfigs::useVrFlinger>(false);
191
Fabien Sanglard1971b632017-03-10 14:50:03 -0800192 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
193 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
194
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600195 hasWideColorDisplay =
196 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
197
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800198 // debugging stuff...
199 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700200
Mathias Agopianb4b17302013-03-20 18:36:41 -0700201 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700202 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204 property_get("debug.sf.showupdates", value, "0");
205 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700206
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700207 property_get("debug.sf.ddms", value, "0");
208 mDebugDDMS = atoi(value);
209 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700210 if (!startDdmConnection()) {
211 // start failed, and DDMS debugging not enabled
212 mDebugDDMS = 0;
213 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700214 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700215 ALOGI_IF(mDebugRegion, "showupdates enabled");
216 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700217
218 property_get("debug.sf.disable_backpressure", value, "0");
219 mPropagateBackpressure = !atoi(value);
220 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700221
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800222 property_get("debug.sf.enable_hwc_vds", value, "0");
223 mUseHwcVirtualDisplays = atoi(value);
224 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800225
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800226 property_get("ro.sf.disable_triple_buffer", value, "1");
227 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800228 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700229
Romain Guy11d63f42017-07-20 12:47:14 -0700230 // We should be reading 'persist.sys.sf.color_saturation' here
231 // but since /data may be encrypted, we need to wait until after vold
232 // comes online to attempt to read the property. The property is
233 // instead read after the boot animation
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234}
235
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800236void SurfaceFlinger::onFirstRef()
237{
238 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800239}
240
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800241SurfaceFlinger::~SurfaceFlinger()
242{
Mathias Agopiana4912602012-07-12 14:25:33 -0700243 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
244 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
245 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800246}
247
Dan Stozac7014012014-02-14 15:03:43 -0800248void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800249{
250 // the window manager died on us. prepare its eulogy.
251
Andy McFadden13a082e2012-08-24 10:16:42 -0700252 // restore initial conditions (default device unblank, etc)
253 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800254
255 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700256 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800257}
258
Robert Carr1db73f62016-12-21 12:58:51 -0800259static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700260 status_t err = client->initCheck();
261 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800262 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800263 }
Robert Carr1db73f62016-12-21 12:58:51 -0800264 return nullptr;
265}
266
267sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
268 return initClient(new Client(this));
269}
270
271sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
272 const sp<IGraphicBufferProducer>& gbp) {
273 if (authenticateSurfaceTexture(gbp) == false) {
274 return nullptr;
275 }
276 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
277 if (layer == nullptr) {
278 return nullptr;
279 }
280
281 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282}
283
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700284sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
285 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700286{
287 class DisplayToken : public BBinder {
288 sp<SurfaceFlinger> flinger;
289 virtual ~DisplayToken() {
290 // no more references, this display must be terminated
291 Mutex::Autolock _l(flinger->mStateLock);
292 flinger->mCurrentState.displays.removeItem(this);
293 flinger->setTransactionFlags(eDisplayTransactionNeeded);
294 }
295 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700296 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700297 : flinger(flinger) {
298 }
299 };
300
301 sp<BBinder> token = new DisplayToken(this);
302
303 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700304 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700305 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700306 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700307 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700308 return token;
309}
310
Jesse Hall6c913be2013-08-08 12:15:49 -0700311void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
312 Mutex::Autolock _l(mStateLock);
313
314 ssize_t idx = mCurrentState.displays.indexOfKey(display);
315 if (idx < 0) {
316 ALOGW("destroyDisplay: invalid display token");
317 return;
318 }
319
320 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
321 if (!info.isVirtualDisplay()) {
322 ALOGE("destroyDisplay called for non-virtual display");
323 return;
324 }
Irvelffc9efc2016-07-27 15:16:37 -0700325 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700326 mCurrentState.displays.removeItemsAt(idx);
327 setTransactionFlags(eDisplayTransactionNeeded);
328}
329
Jesse Hall692c7232012-11-08 15:41:56 -0800330void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800331 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800332 ALOGW_IF(mBuiltinDisplays[type],
333 "Overwriting display token for display type %d", type);
334 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800335 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700336 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800337 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700338 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800339}
340
Mathias Agopiane57f2922012-08-09 16:29:12 -0700341sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700342 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700343 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
344 return NULL;
345 }
Jesse Hall692c7232012-11-08 15:41:56 -0800346 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700347}
348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349void SurfaceFlinger::bootFinished()
350{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700351 if (mStartPropertySetThread->join() != NO_ERROR) {
352 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 const nsecs_t now = systemTime();
355 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000356 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700357
358 // wait patiently for the window manager death
359 const String16 name("window");
360 sp<IBinder> window(defaultServiceManager()->getService(name));
361 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700362 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700363 }
364
Steven Thomas050b2c82017-03-06 11:45:16 -0800365 if (mVrFlinger) {
366 mVrFlinger->OnBootFinished();
367 }
368
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700369 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700370 // formerly we would just kill the process, but we now ask it to exit so it
371 // can choose where to stop the animation.
372 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700373
374 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
375 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
376 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700377
Romain Guyc53d3552017-07-20 18:49:46 -0700378 sp<LambdaMessage> bootFinished = new LambdaMessage([&]() {
379 mBootFinished = true;
380
Romain Guy11d63f42017-07-20 12:47:14 -0700381 readPersistentProperties();
Romain Guyc53d3552017-07-20 18:49:46 -0700382
383#ifdef USE_HWC2
384 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
385 if (hw->getWideColorSupport()) {
Courtney Goeltzenleuchter281e8112017-07-13 17:54:01 -0600386 hw->setCompositionDataSpace(HAL_DATASPACE_V0_SRGB);
Romain Guyc53d3552017-07-20 18:49:46 -0700387 setActiveColorModeInternal(hw, HAL_COLOR_MODE_SRGB);
388 }
389#endif
Romain Guy11d63f42017-07-20 12:47:14 -0700390 });
Romain Guyc53d3552017-07-20 18:49:46 -0700391 postMessageAsync(bootFinished);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800392}
393
Mathias Agopian3f844832013-08-07 21:24:32 -0700394void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700395 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700396 RenderEngine& engine;
397 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700398 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700399 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
400 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700401 }
402 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700403 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700404 return true;
405 }
406 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700407 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700408}
409
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700410class DispSyncSource : public VSyncSource, private DispSync::Callback {
411public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700412 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000413 const char* name) :
414 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700415 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700416 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000417 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
418 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700419 mDispSync(dispSync),
420 mCallbackMutex(),
421 mCallback(),
422 mVsyncMutex(),
423 mPhaseOffset(phaseOffset),
424 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700425
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700426 virtual ~DispSyncSource() {}
427
428 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700429 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700430 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000431 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 static_cast<DispSync::Callback*>(this));
433 if (err != NO_ERROR) {
434 ALOGE("error registering vsync callback: %s (%d)",
435 strerror(-err), err);
436 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700437 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 } else {
439 status_t err = mDispSync->removeEventListener(
440 static_cast<DispSync::Callback*>(this));
441 if (err != NO_ERROR) {
442 ALOGE("error unregistering vsync callback: %s (%d)",
443 strerror(-err), err);
444 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700445 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700447 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700448 }
449
450 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700451 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452 mCallback = callback;
453 }
454
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700455 virtual void setPhaseOffset(nsecs_t phaseOffset) {
456 Mutex::Autolock lock(mVsyncMutex);
457
458 // Normalize phaseOffset to [0, period)
459 auto period = mDispSync->getPeriod();
460 phaseOffset %= period;
461 if (phaseOffset < 0) {
462 // If we're here, then phaseOffset is in (-period, 0). After this
463 // operation, it will be in (0, period)
464 phaseOffset += period;
465 }
466 mPhaseOffset = phaseOffset;
467
468 // If we're not enabled, we don't need to mess with the listeners
469 if (!mEnabled) {
470 return;
471 }
472
473 // Remove the listener with the old offset
474 status_t err = mDispSync->removeEventListener(
475 static_cast<DispSync::Callback*>(this));
476 if (err != NO_ERROR) {
477 ALOGE("error unregistering vsync callback: %s (%d)",
478 strerror(-err), err);
479 }
480
481 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000482 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700483 static_cast<DispSync::Callback*>(this));
484 if (err != NO_ERROR) {
485 ALOGE("error registering vsync callback: %s (%d)",
486 strerror(-err), err);
487 }
488 }
489
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700490private:
491 virtual void onDispSyncEvent(nsecs_t when) {
492 sp<VSyncSource::Callback> callback;
493 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700494 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700495 callback = mCallback;
496
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700497 if (mTraceVsync) {
498 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700499 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700500 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501 }
502
503 if (callback != NULL) {
504 callback->onVSyncEvent(when);
505 }
506 }
507
Tim Murray4a4e4a22016-04-19 16:29:23 +0000508 const char* const mName;
509
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510 int mValue;
511
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700512 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700513 const String8 mVsyncOnLabel;
514 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700515
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700517
518 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700519 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700520
521 Mutex mVsyncMutex; // Protects the following
522 nsecs_t mPhaseOffset;
523 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700524};
525
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700526class InjectVSyncSource : public VSyncSource {
527public:
528 InjectVSyncSource() {}
529
530 virtual ~InjectVSyncSource() {}
531
532 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
533 std::lock_guard<std::mutex> lock(mCallbackMutex);
534 mCallback = callback;
535 }
536
537 virtual void onInjectSyncEvent(nsecs_t when) {
538 std::lock_guard<std::mutex> lock(mCallbackMutex);
539 mCallback->onVSyncEvent(when);
540 }
541
542 virtual void setVSyncEnabled(bool) {}
543 virtual void setPhaseOffset(nsecs_t) {}
544
545private:
546 std::mutex mCallbackMutex; // Protects the following
547 sp<VSyncSource::Callback> mCallback;
548};
549
Wei Wangf9b05ee2017-07-19 20:59:39 -0700550// Do not call property_set on main thread which will be blocked by init
551// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700553 ALOGI( "SurfaceFlinger's main thread ready to run. "
554 "Initializing graphics H/W...");
555
Romain Guyc53d3552017-07-20 18:49:46 -0700556 ALOGI("Phase offset NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900557
Dan Stoza9e56aa02015-11-02 13:00:03 -0800558 { // Autolock scope
559 Mutex::Autolock _l(mStateLock);
560
561 // initialize EGL for the default display
562 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
563 eglInitialize(mEGLDisplay, NULL, NULL);
564
565 // start the EventThread
566 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
567 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700568 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800569 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
570 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700571 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800572 mEventQueue.setEventThread(mSFEventThread);
573
Tim Murray22752852017-05-04 13:38:49 -0700574 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700575 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700576 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700577 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
578 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
579 }
Tim Murray22752852017-05-04 13:38:49 -0700580 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
581 ALOGE("Couldn't set SCHED_FIFO for EventThread");
582 }
Tim Murray41a38532016-06-22 12:42:10 -0700583
Dan Stoza9e56aa02015-11-02 13:00:03 -0800584 // Get a RenderEngine for the given display / config (can't fail)
585 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700586 HAL_PIXEL_FORMAT_RGBA_8888,
587 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800588 }
589
590 // Drop the state lock while we initialize the hardware composer. We drop
591 // the lock because on creation, it will call back into SurfaceFlinger to
592 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800593 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
594 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800595 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800596 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800597 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
598
Jesse Hall692c7232012-11-08 15:41:56 -0800599 Mutex::Autolock _l(mStateLock);
600
Steven Thomas050b2c82017-03-06 11:45:16 -0800601 if (useVrFlinger) {
602 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700603 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800604 mVrFlingerRequestsDisplay = requestDisplay;
605 signalTransaction();
606 };
607 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
608 vrFlingerRequestDisplayCallback);
609 if (!mVrFlinger) {
610 ALOGE("Failed to start vrflinger");
611 }
612 }
613
Mathias Agopian875d8e12013-06-07 15:35:48 -0700614 // retrieve the EGL context that was selected/created
615 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700616
Mathias Agopianda27af92012-09-13 18:17:13 -0700617 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
618 "couldn't create EGLContext");
619
Dan Stoza9e56aa02015-11-02 13:00:03 -0800620 // make the GLContext current so that we can create textures when creating
621 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700622 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700623
Jamie Gennisd1700752013-10-14 12:22:52 -0700624 mEventControlThread = new EventControlThread(this);
625 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
626
Mathias Agopian92a979a2012-08-02 18:32:23 -0700627 // initialize our drawing state
628 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700629
Andy McFadden13a082e2012-08-24 10:16:42 -0700630 // set initial conditions (e.g. unblank default device)
631 initializeDisplays();
632
Dan Stoza4e637772016-07-28 13:31:51 -0700633 mRenderEngine->primeCache();
634
Wei Wangf9b05ee2017-07-19 20:59:39 -0700635 // Inform native graphics APIs whether the present timestamp is supported:
636 if (getHwComposer().hasCapability(
637 HWC2::Capability::PresentFenceIsNotReliable)) {
638 mStartPropertySetThread = new StartPropertySetThread(false);
639 } else {
640 mStartPropertySetThread = new StartPropertySetThread(true);
641 }
642
643 if (mStartPropertySetThread->Start() != NO_ERROR) {
644 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800645 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800646
Dan Stoza9e56aa02015-11-02 13:00:03 -0800647 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700648}
649
Romain Guy11d63f42017-07-20 12:47:14 -0700650void SurfaceFlinger::readPersistentProperties() {
651 char value[PROPERTY_VALUE_MAX];
652
653 property_get("persist.sys.sf.color_saturation", value, "1.0");
654 mSaturation = atof(value);
655 ALOGV("Saturation is set to %.2f", mSaturation);
656}
657
Mathias Agopiana67e4182012-06-19 17:26:12 -0700658void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800659 // Start boot animation service by setting a property mailbox
660 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700661 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800662 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700663 if (mStartPropertySetThread->join() != NO_ERROR) {
664 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800665 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700666}
667
Mathias Agopian875d8e12013-06-07 15:35:48 -0700668size_t SurfaceFlinger::getMaxTextureSize() const {
669 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700670}
671
Mathias Agopian875d8e12013-06-07 15:35:48 -0700672size_t SurfaceFlinger::getMaxViewportDims() const {
673 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700674}
675
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800676// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800677
Jamie Gennis582270d2011-08-17 18:19:00 -0700678bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800679 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800680 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800681 return authenticateSurfaceTextureLocked(bufferProducer);
682}
683
684bool SurfaceFlinger::authenticateSurfaceTextureLocked(
685 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800686 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700687 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800688}
689
Brian Anderson6b376712017-04-04 10:51:39 -0700690status_t SurfaceFlinger::getSupportedFrameTimestamps(
691 std::vector<FrameEvent>* outSupported) const {
692 *outSupported = {
693 FrameEvent::REQUESTED_PRESENT,
694 FrameEvent::ACQUIRE,
695 FrameEvent::LATCH,
696 FrameEvent::FIRST_REFRESH_START,
697 FrameEvent::LAST_REFRESH_START,
698 FrameEvent::GPU_COMPOSITION_DONE,
699 FrameEvent::DEQUEUE_READY,
700 FrameEvent::RELEASE,
701 };
702 if (!getHwComposer().hasCapability(
703 HWC2::Capability::PresentFenceIsNotReliable)) {
704 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
705 }
706 return NO_ERROR;
707}
708
Dan Stoza7f7da322014-05-02 15:26:25 -0700709status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
710 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700711 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700712 return BAD_VALUE;
713 }
714
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500715 if (!display.get())
716 return NAME_NOT_FOUND;
717
Jesse Hall692c7232012-11-08 15:41:56 -0800718 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700719 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800720 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700721 type = i;
722 break;
723 }
724 }
725
726 if (type < 0) {
727 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700728 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700729
Mathias Agopian8b736f12012-08-13 17:54:26 -0700730 // TODO: Not sure if display density should handled by SF any longer
731 class Density {
732 static int getDensityFromProperty(char const* propName) {
733 char property[PROPERTY_VALUE_MAX];
734 int density = 0;
735 if (property_get(propName, property, NULL) > 0) {
736 density = atoi(property);
737 }
738 return density;
739 }
740 public:
741 static int getEmuDensity() {
742 return getDensityFromProperty("qemu.sf.lcd_density"); }
743 static int getBuildDensity() {
744 return getDensityFromProperty("ro.sf.lcd_density"); }
745 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700746
Dan Stoza7f7da322014-05-02 15:26:25 -0700747 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700748
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700750 DisplayInfo info = DisplayInfo();
751
Dan Stoza9e56aa02015-11-02 13:00:03 -0800752 float xdpi = hwConfig->getDpiX();
753 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700754
755 if (type == DisplayDevice::DISPLAY_PRIMARY) {
756 // The density of the device is provided by a build property
757 float density = Density::getBuildDensity() / 160.0f;
758 if (density == 0) {
759 // the build doesn't provide a density -- this is wrong!
760 // use xdpi instead
761 ALOGE("ro.sf.lcd_density must be defined as a build property");
762 density = xdpi / 160.0f;
763 }
764 if (Density::getEmuDensity()) {
765 // if "qemu.sf.lcd_density" is specified, it overrides everything
766 xdpi = ydpi = density = Density::getEmuDensity();
767 density /= 160.0f;
768 }
769 info.density = density;
770
771 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000772 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
773 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700774 } else {
775 // TODO: where should this value come from?
776 static const int TV_DENSITY = 213;
777 info.density = TV_DENSITY / 160.0f;
778 info.orientation = 0;
779 }
780
Dan Stoza9e56aa02015-11-02 13:00:03 -0800781 info.w = hwConfig->getWidth();
782 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700783 info.xdpi = xdpi;
784 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800785 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900786 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800787
Andy McFadden91b2ca82014-06-13 14:04:23 -0700788 // This is how far in advance a buffer must be queued for
789 // presentation at a given time. If you want a buffer to appear
790 // on the screen at time N, you must submit the buffer before
791 // (N - presentationDeadline).
792 //
793 // Normally it's one full refresh period (to give SF a chance to
794 // latch the buffer), but this can be reduced by configuring a
795 // DispSync offset. Any additional delays introduced by the hardware
796 // composer or panel must be accounted for here.
797 //
798 // We add an additional 1ms to allow for processing time and
799 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800801 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700802
803 // All non-virtual displays are currently considered secure.
804 info.secure = true;
805
Michael Wright28f24d02016-07-12 13:30:53 -0700806 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700807 }
808
Dan Stoza7f7da322014-05-02 15:26:25 -0700809 return NO_ERROR;
810}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700811
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800812status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700813 DisplayStatInfo* stats) {
814 if (stats == NULL) {
815 return BAD_VALUE;
816 }
817
818 // FIXME for now we always return stats for the primary display
819 memset(stats, 0, sizeof(*stats));
820 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
821 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
822 return NO_ERROR;
823}
824
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700825int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800826 if (display == NULL) {
827 ALOGE("%s : display is NULL", __func__);
828 return BAD_VALUE;
829 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700830
831 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700832 if (device != NULL) {
833 return device->getActiveConfig();
834 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700835
Dan Stoza24a42e92015-03-09 10:04:11 -0700836 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700837}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700838
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700839void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
840 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
841 this);
842 int32_t type = hw->getDisplayType();
843 int currentMode = hw->getActiveConfig();
844
845 if (mode == currentMode) {
846 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
847 return;
848 }
849
850 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
851 ALOGW("Trying to set config for virtual display");
852 return;
853 }
854
855 hw->setActiveConfig(mode);
856 getHwComposer().setActiveConfig(type, mode);
857}
858
859status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
860 class MessageSetActiveConfig: public MessageBase {
861 SurfaceFlinger& mFlinger;
862 sp<IBinder> mDisplay;
863 int mMode;
864 public:
865 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
866 int mode) :
867 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
868 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700869 Vector<DisplayInfo> configs;
870 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700871 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700872 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700873 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700874 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700875 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700876 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
877 if (hw == NULL) {
878 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700879 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700880 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
881 ALOGW("Attempt to set active config = %d for virtual display",
882 mMode);
883 } else {
884 mFlinger.setActiveConfigInternal(hw, mMode);
885 }
886 return true;
887 }
888 };
889 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
890 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700891 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700892}
Michael Wright28f24d02016-07-12 13:30:53 -0700893status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
894 Vector<android_color_mode_t>* outColorModes) {
895 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
896 return BAD_VALUE;
897 }
898
899 if (!display.get()) {
900 return NAME_NOT_FOUND;
901 }
902
903 int32_t type = NAME_NOT_FOUND;
904 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
905 if (display == mBuiltinDisplays[i]) {
906 type = i;
907 break;
908 }
909 }
910
911 if (type < 0) {
912 return type;
913 }
914
915 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
916 outColorModes->clear();
917 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
918
919 return NO_ERROR;
920}
921
922android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700923 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700924 if (device != nullptr) {
925 return device->getActiveColorMode();
926 }
927 return static_cast<android_color_mode_t>(BAD_VALUE);
928}
929
930void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
931 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700932 int32_t type = hw->getDisplayType();
933 android_color_mode_t currentMode = hw->getActiveColorMode();
934
935 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700936 return;
937 }
938
939 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
940 ALOGW("Trying to set config for virtual display");
941 return;
942 }
943
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600944 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
945 hw->getDisplayType());
946
Michael Wright28f24d02016-07-12 13:30:53 -0700947 hw->setActiveColorMode(mode);
948 getHwComposer().setActiveColorMode(type, mode);
949}
950
951
952status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
953 android_color_mode_t colorMode) {
954 class MessageSetActiveColorMode: public MessageBase {
955 SurfaceFlinger& mFlinger;
956 sp<IBinder> mDisplay;
957 android_color_mode_t mMode;
958 public:
959 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
960 android_color_mode_t mode) :
961 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
962 virtual bool handler() {
963 Vector<android_color_mode_t> modes;
964 mFlinger.getDisplayColorModes(mDisplay, &modes);
965 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
966 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600967 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
968 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700969 return true;
970 }
971 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
972 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600973 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
974 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700975 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600976 ALOGW("Attempt to set active color mode %s %d for virtual display",
977 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700978 } else {
979 mFlinger.setActiveColorModeInternal(hw, mMode);
980 }
981 return true;
982 }
983 };
984 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
985 postMessageSync(msg);
986 return NO_ERROR;
987}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700988
Svetoslavd85084b2014-03-20 10:28:31 -0700989status_t SurfaceFlinger::clearAnimationFrameStats() {
990 Mutex::Autolock _l(mStateLock);
991 mAnimFrameTracker.clearStats();
992 return NO_ERROR;
993}
994
995status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
996 Mutex::Autolock _l(mStateLock);
997 mAnimFrameTracker.getStats(outStats);
998 return NO_ERROR;
999}
1000
Dan Stozac4f471e2016-03-24 09:31:08 -07001001status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1002 HdrCapabilities* outCapabilities) const {
1003 Mutex::Autolock _l(mStateLock);
1004
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001005 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001006 if (displayDevice == nullptr) {
1007 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1008 return BAD_VALUE;
1009 }
1010
1011 std::unique_ptr<HdrCapabilities> capabilities =
1012 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1013 if (capabilities) {
1014 std::swap(*outCapabilities, *capabilities);
1015 } else {
1016 return BAD_VALUE;
1017 }
1018
1019 return NO_ERROR;
1020}
1021
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001022status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1023 if (enable == mInjectVSyncs) {
1024 return NO_ERROR;
1025 }
1026
1027 if (enable) {
1028 mInjectVSyncs = enable;
1029 ALOGV("VSync Injections enabled");
1030 if (mVSyncInjector.get() == nullptr) {
1031 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001032 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001033 }
1034 mEventQueue.setEventThread(mInjectorEventThread);
1035 } else {
1036 mInjectVSyncs = enable;
1037 ALOGV("VSync Injections disabled");
1038 mEventQueue.setEventThread(mSFEventThread);
1039 mVSyncInjector.clear();
1040 }
1041 return NO_ERROR;
1042}
1043
1044status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1045 if (!mInjectVSyncs) {
1046 ALOGE("VSync Injections not enabled");
1047 return BAD_VALUE;
1048 }
1049 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1050 ALOGV("Injecting VSync inside SurfaceFlinger");
1051 mVSyncInjector->onInjectSyncEvent(when);
1052 }
1053 return NO_ERROR;
1054}
1055
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001056// ----------------------------------------------------------------------------
1057
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001058sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1059 ISurfaceComposer::VsyncSource vsyncSource) {
1060 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1061 return mSFEventThread->createEventConnection();
1062 } else {
1063 return mEventThread->createEventConnection();
1064 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001065}
1066
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001067// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001068
1069void SurfaceFlinger::waitForEvent() {
1070 mEventQueue.waitMessage();
1071}
1072
1073void SurfaceFlinger::signalTransaction() {
1074 mEventQueue.invalidate();
1075}
1076
1077void SurfaceFlinger::signalLayerUpdate() {
1078 mEventQueue.invalidate();
1079}
1080
1081void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001082 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001083 mEventQueue.refresh();
1084}
1085
1086status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001087 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001088 return mEventQueue.postMessage(msg, reltime);
1089}
1090
1091status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001092 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001093 status_t res = mEventQueue.postMessage(msg, reltime);
1094 if (res == NO_ERROR) {
1095 msg->wait();
1096 }
1097 return res;
1098}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001099
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001100void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001101 do {
1102 waitForEvent();
1103 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001104}
1105
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001106void SurfaceFlinger::enableHardwareVsync() {
1107 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001108 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001109 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001110 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1111 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001112 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001113 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001114}
1115
Jesse Hall948fe0c2013-10-14 12:56:09 -07001116void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001117 Mutex::Autolock _l(mHWVsyncLock);
1118
Jesse Hall948fe0c2013-10-14 12:56:09 -07001119 if (makeAvailable) {
1120 mHWVsyncAvailable = true;
1121 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001122 // Hardware vsync is not currently available, so abort the resync
1123 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001124 return;
1125 }
1126
Dan Stoza9e56aa02015-11-02 13:00:03 -08001127 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1128 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001129
1130 mPrimaryDispSync.reset();
1131 mPrimaryDispSync.setPeriod(period);
1132
1133 if (!mPrimaryHWVsyncEnabled) {
1134 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001135 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1136 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001137 mPrimaryHWVsyncEnabled = true;
1138 }
1139}
1140
Jesse Hall948fe0c2013-10-14 12:56:09 -07001141void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001142 Mutex::Autolock _l(mHWVsyncLock);
1143 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001144 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1145 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001146 mPrimaryDispSync.endResync();
1147 mPrimaryHWVsyncEnabled = false;
1148 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001149 if (makeUnavailable) {
1150 mHWVsyncAvailable = false;
1151 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001152}
1153
Tim Murray4a4e4a22016-04-19 16:29:23 +00001154void SurfaceFlinger::resyncWithRateLimit() {
1155 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001156
1157 // No explicit locking is needed here since EventThread holds a lock while calling this method
1158 static nsecs_t sLastResyncAttempted = 0;
1159 const nsecs_t now = systemTime();
1160 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001161 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001162 }
Dan Stoza57164302017-05-08 14:03:54 -07001163 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001164}
1165
Steven Thomas3cfac282017-02-06 12:29:30 -08001166void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1167 nsecs_t timestamp) {
1168 Mutex::Autolock lock(mStateLock);
1169 // Ignore any vsyncs from the non-active hardware composer.
1170 if (composer != mHwc) {
1171 return;
1172 }
1173
Jamie Gennisd1700752013-10-14 12:22:52 -07001174 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001175
Jamie Gennisd1700752013-10-14 12:22:52 -07001176 { // Scope for the lock
1177 Mutex::Autolock _l(mHWVsyncLock);
1178 if (type == 0 && mPrimaryHWVsyncEnabled) {
1179 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001180 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001181 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001182
1183 if (needsHwVsync) {
1184 enableHardwareVsync();
1185 } else {
1186 disableHardwareVsync(false);
1187 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001188}
1189
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001190void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001191 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001192 *compositorTiming = mCompositorTiming;
1193}
1194
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001195void SurfaceFlinger::createDefaultDisplayDevice() {
1196 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1197 wp<IBinder> token = mBuiltinDisplays[type];
1198
1199 // All non-virtual displays are currently considered secure.
1200 const bool isSecure = true;
1201
1202 sp<IGraphicBufferProducer> producer;
1203 sp<IGraphicBufferConsumer> consumer;
1204 BufferQueue::createBufferQueue(&producer, &consumer);
1205
1206 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1207
1208 bool hasWideColorModes = false;
1209 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1210 for (android_color_mode_t colorMode : modes) {
1211 switch (colorMode) {
1212 case HAL_COLOR_MODE_DISPLAY_P3:
1213 case HAL_COLOR_MODE_ADOBE_RGB:
1214 case HAL_COLOR_MODE_DCI_P3:
1215 hasWideColorModes = true;
1216 break;
1217 default:
1218 break;
1219 }
1220 }
1221 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1222 token, fbs, producer, mRenderEngine->getEGLConfig(),
1223 hasWideColorModes && hasWideColorDisplay);
1224 mDisplays.add(token, hw);
Romain Guyc53d3552017-07-20 18:49:46 -07001225 setActiveColorModeInternal(hw, HAL_COLOR_MODE_NATIVE);
Courtney Goeltzenleuchter281e8112017-07-13 17:54:01 -06001226 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001227}
1228
1229void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001230 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001231
1232 if (composer->isUsingVrComposer()) {
1233 // We handle initializing the primary display device for the VR
1234 // window manager hwc explicitly at the time of transition.
1235 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1236 ALOGE("External displays are not supported by the vr hardware composer.");
1237 }
1238 return;
1239 }
1240
Dan Stoza9e56aa02015-11-02 13:00:03 -08001241 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1242 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001243 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1244 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001245 } else {
1246 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001247 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001248 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001249 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001250 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001251 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1252 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001253 }
1254 setTransactionFlags(eDisplayTransactionNeeded);
1255
Andy McFadden9e9689c2012-10-10 18:17:51 -07001256 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001257 }
Mathias Agopian86303202012-07-24 22:46:10 -07001258}
1259
Steven Thomas3cfac282017-02-06 12:29:30 -08001260void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1261 Mutex::Autolock lock(mStateLock);
1262 if (composer == mHwc) {
1263 repaintEverything();
1264 } else {
1265 // This isn't from our current hardware composer. If it's a callback
1266 // from the real composer, forward the refresh request to vr
1267 // flinger. Otherwise ignore it.
1268 if (!composer->isUsingVrComposer()) {
1269 mVrFlinger->OnHardwareComposerRefresh();
1270 }
1271 }
1272}
1273
Dan Stoza9e56aa02015-11-02 13:00:03 -08001274void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001276 getHwComposer().setVsyncEnabled(disp,
1277 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001278}
1279
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001280// Note: it is assumed the caller holds |mStateLock| when this is called
1281void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001282 disableHardwareVsync(true);
1283 clearHwcLayers(mDrawingState.layersSortedByZ);
1284 clearHwcLayers(mCurrentState.layersSortedByZ);
Steven Thomasf5a5f6e2017-07-17 13:59:23 -07001285 for (size_t disp = 0; disp < mDisplays.size(); ++disp) {
1286 clearHwcLayers(mDisplays[disp]->getVisibleLayersSortedByZ());
1287 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001288 // Clear the drawing state so that the logic inside of
1289 // handleTransactionLocked will fire. It will determine the delta between
1290 // mCurrentState and mDrawingState and re-apply all changes when we make the
1291 // transition.
1292 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001293 // Release virtual display hwcId during vr mode transition.
1294 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1295 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1296 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1297 displayDevice->disconnect(getHwComposer());
1298 }
1299 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001300 mDisplays.clear();
1301}
1302
Steven Thomas050b2c82017-03-06 11:45:16 -08001303void SurfaceFlinger::updateVrFlinger() {
1304 if (!mVrFlinger)
1305 return;
1306 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1307 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001308 return;
1309 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001310
Steven Thomas050b2c82017-03-06 11:45:16 -08001311 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001312 // Construct new HWComposer without holding any locks.
1313 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001314
1315 // Set up the event handlers. This step is neccessary to initialize the internal state of
1316 // the hardware composer object properly. Our callbacks are designed such that if they are
1317 // triggered between now and the point where the display is properly re-initialized, they
1318 // will not have any effect, so this is safe to do here, before the lock is aquired.
1319 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001320 ALOGV("Vr HWC created");
1321 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001322
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001323 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001324
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001325 if (vrFlingerRequestsDisplay) {
1326 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001327
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001328 mHwc = mVrHwc;
1329 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001330
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001331 } else {
1332 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001333
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001334 resetHwcLocked();
1335
1336 mHwc = mRealHwc;
1337 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001338 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001339
1340 mVisibleRegionsDirty = true;
1341 invalidateHwcGeometry();
1342
1343 // Explicitly re-initialize the primary display. This is because some other
1344 // parts of this class rely on the primary display always being available.
1345 createDefaultDisplayDevice();
1346
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001347 // Re-enable default display.
1348 sp<LambdaMessage> requestMessage = new LambdaMessage([&]() {
1349 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1350 setPowerModeInternal(hw, HWC_POWER_MODE_NORMAL);
1351
1352 // Reset the timing values to account for the period of the swapped in HWC
1353 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1354 const nsecs_t period = activeConfig->getVsyncPeriod();
1355 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1356
1357 // Use phase of 0 since phase is not known.
1358 // Use latency of 0, which will snap to the ideal latency.
1359 setCompositorTimingSnapped(0, period, 0);
1360 });
1361 postMessageAsync(requestMessage);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001362
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001363 android_atomic_or(1, &mRepaintEverything);
1364 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001365}
1366
Mathias Agopian4fec8732012-06-29 14:12:52 -07001367void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001368 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001369 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001370 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001371 bool frameMissed = !mHadClientComposition &&
1372 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001373 (mPreviousPresentFence->getSignalTime() ==
1374 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001375 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001376 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001377 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001378 signalLayerUpdate();
1379 break;
1380 }
1381
Steven Thomas050b2c82017-03-06 11:45:16 -08001382 // Now that we're going to make it to the handleMessageTransaction()
1383 // call below it's safe to call updateVrFlinger(), which will
1384 // potentially trigger a display handoff.
1385 updateVrFlinger();
1386
Dan Stoza6b9454d2014-11-07 16:00:59 -08001387 bool refreshNeeded = handleMessageTransaction();
1388 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001389 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001390 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001391 // Signal a refresh if a transaction modified the window state,
1392 // a new buffer was latched, or if HWC has requested a full
1393 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001394 signalRefresh();
1395 }
1396 break;
1397 }
1398 case MessageQueue::REFRESH: {
1399 handleMessageRefresh();
1400 break;
1401 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001402 }
1403}
1404
Dan Stoza6b9454d2014-11-07 16:00:59 -08001405bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001406 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001407 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001408 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001409 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001410 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001411 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001412}
1413
Dan Stoza6b9454d2014-11-07 16:00:59 -08001414bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001415 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001416 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001417}
1418
1419void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001420 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001421
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001422 mRefreshPending = false;
1423
Pablo Ceballos40845df2016-01-25 17:41:15 -08001424 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001425
Brian Andersond6927fb2016-07-23 23:37:30 -07001426 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001427 rebuildLayerStacks();
1428 setUpHWComposer();
1429 doDebugFlashRegions();
1430 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001431 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001432
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001433 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001434
1435 mHadClientComposition = false;
1436 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1437 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1438 mHadClientComposition = mHadClientComposition ||
1439 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1440 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001441
Dan Stoza9e56aa02015-11-02 13:00:03 -08001442 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001443}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001444
Mathias Agopiancd60f992012-08-16 16:28:27 -07001445void SurfaceFlinger::doDebugFlashRegions()
1446{
1447 // is debugging enabled
1448 if (CC_LIKELY(!mDebugRegion))
1449 return;
1450
1451 const bool repaintEverything = mRepaintEverything;
1452 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1453 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001454 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001455 // transform the dirty region into this screen's coordinate space
1456 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1457 if (!dirtyRegion.isEmpty()) {
1458 // redraw the whole screen
1459 doComposeSurfaces(hw, Region(hw->bounds()));
1460
1461 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001462 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001463 RenderEngine& engine(getRenderEngine());
1464 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1465
Mathias Agopianda27af92012-09-13 18:17:13 -07001466 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001467 }
1468 }
1469 }
1470
1471 postFramebuffer();
1472
1473 if (mDebugRegion > 1) {
1474 usleep(mDebugRegion * 1000);
1475 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001476
Dan Stoza9e56aa02015-11-02 13:00:03 -08001477 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001478 auto& displayDevice = mDisplays[displayId];
1479 if (!displayDevice->isDisplayOn()) {
1480 continue;
1481 }
1482
1483 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001484 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1485 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001486 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001487}
1488
Brian Andersond6927fb2016-07-23 23:37:30 -07001489void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001490{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001491 ATRACE_CALL();
1492 ALOGV("preComposition");
1493
Mathias Agopiancd60f992012-08-16 16:28:27 -07001494 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001495 mDrawingState.traverseInZOrder([&](Layer* layer) {
1496 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001497 needExtraInvalidate = true;
1498 }
Robert Carr2047fae2016-11-28 14:09:09 -08001499 });
1500
Mathias Agopiancd60f992012-08-16 16:28:27 -07001501 if (needExtraInvalidate) {
1502 signalLayerUpdate();
1503 }
1504}
1505
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001506void SurfaceFlinger::updateCompositorTiming(
1507 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1508 std::shared_ptr<FenceTime>& presentFenceTime) {
1509 // Update queue of past composite+present times and determine the
1510 // most recently known composite to present latency.
1511 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1512 nsecs_t compositeToPresentLatency = -1;
1513 while (!mCompositePresentTimes.empty()) {
1514 CompositePresentTime& cpt = mCompositePresentTimes.front();
1515 // Cached values should have been updated before calling this method,
1516 // which helps avoid duplicate syscalls.
1517 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1518 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1519 break;
1520 }
1521 compositeToPresentLatency = displayTime - cpt.composite;
1522 mCompositePresentTimes.pop();
1523 }
1524
1525 // Don't let mCompositePresentTimes grow unbounded, just in case.
1526 while (mCompositePresentTimes.size() > 16) {
1527 mCompositePresentTimes.pop();
1528 }
1529
Brian Andersond0010582017-03-07 13:20:31 -08001530 setCompositorTimingSnapped(
1531 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1532}
1533
1534void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1535 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001536 // Integer division and modulo round toward 0 not -inf, so we need to
1537 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001538 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001539 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1540 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1541
Brian Andersond0010582017-03-07 13:20:31 -08001542 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1543 if (idealLatency <= 0) {
1544 idealLatency = vsyncInterval;
1545 }
1546
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001547 // Snap the latency to a value that removes scheduling jitter from the
1548 // composition and present times, which often have >1ms of jitter.
1549 // Reducing jitter is important if an app attempts to extrapolate
1550 // something (such as user input) to an accurate diasplay time.
1551 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1552 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001553 nsecs_t bias = vsyncInterval / 2;
1554 int64_t extraVsyncs =
1555 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1556 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1557 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001558
Brian Andersond0010582017-03-07 13:20:31 -08001559 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001560 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1561 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001562 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001563}
1564
1565void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001567 ATRACE_CALL();
1568 ALOGV("postComposition");
1569
Brian Anderson3546a3f2016-07-14 11:51:14 -07001570 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001571 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001572 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001573 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001574 }
1575
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001576 // |mStateLock| not needed as we are on the main thread
1577 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001578
1579 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1580 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1581 glCompositionDoneFenceTime =
1582 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1583 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1584 } else {
1585 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1586 }
1587 mGlCompositionDoneTimeline.updateSignalTimes();
1588
Brian Anderson4e606e32017-03-16 15:34:57 -07001589 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1590 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1591 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001592 mDisplayTimeline.updateSignalTimes();
1593
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001594 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1595 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1596
1597 // We use the refreshStartTime which might be sampled a little later than
1598 // when we started doing work for this frame, but that should be okay
1599 // since updateCompositorTiming has snapping logic.
1600 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001601 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001602 CompositorTiming compositorTiming;
1603 {
1604 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1605 compositorTiming = mCompositorTiming;
1606 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001607
Robert Carr2047fae2016-11-28 14:09:09 -08001608 mDrawingState.traverseInZOrder([&](Layer* layer) {
1609 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001610 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001611 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001612 recordBufferingStats(layer->getName().string(),
1613 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001614 }
Robert Carr2047fae2016-11-28 14:09:09 -08001615 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001616
Brian Anderson4e606e32017-03-16 15:34:57 -07001617 if (presentFence->isValid()) {
1618 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001619 enableHardwareVsync();
1620 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001621 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001622 }
1623 }
1624
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001625 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001626 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001627 enableHardwareVsync();
1628 }
1629 }
1630
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001631 if (mAnimCompositionPending) {
1632 mAnimCompositionPending = false;
1633
Brian Anderson4e606e32017-03-16 15:34:57 -07001634 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001635 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001636 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001637 } else {
1638 // The HWC doesn't support present fences, so use the refresh
1639 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001640 nsecs_t presentTime =
1641 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001642 mAnimFrameTracker.setActualPresentTime(presentTime);
1643 }
1644 mAnimFrameTracker.advanceFrame();
1645 }
Dan Stozab90cf072015-03-05 11:05:59 -08001646
1647 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1648 return;
1649 }
1650
1651 nsecs_t currentTime = systemTime();
1652 if (mHasPoweredOff) {
1653 mHasPoweredOff = false;
1654 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001655 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001657 if (numPeriods < NUM_BUCKETS - 1) {
1658 mFrameBuckets[numPeriods] += elapsedTime;
1659 } else {
1660 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1661 }
1662 mTotalTime += elapsedTime;
1663 }
1664 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001665}
1666
1667void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001668 ATRACE_CALL();
1669 ALOGV("rebuildLayerStacks");
1670
Mathias Agopiancd60f992012-08-16 16:28:27 -07001671 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001672 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1673 ATRACE_CALL();
1674 mVisibleRegionsDirty = false;
1675 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001676
Jeff Sharkey76488112017-02-27 14:15:18 -07001677 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1678 Region opaqueRegion;
1679 Region dirtyRegion;
1680 Vector<sp<Layer>> layersSortedByZ;
1681 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1682 const Transform& tr(displayDevice->getTransform());
1683 const Rect bounds(displayDevice->getBounds());
1684 if (displayDevice->isDisplayOn()) {
1685 computeVisibleRegions(
1686 displayDevice->getLayerStack(), dirtyRegion,
1687 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001688
Jeff Sharkey76488112017-02-27 14:15:18 -07001689 mDrawingState.traverseInZOrder([&](Layer* layer) {
1690 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1691 Region drawRegion(tr.transform(
1692 layer->visibleNonTransparentRegion));
1693 drawRegion.andSelf(bounds);
1694 if (!drawRegion.isEmpty()) {
1695 layersSortedByZ.add(layer);
1696 } else {
1697 // Clear out the HWC layer if this layer was
1698 // previously visible, but no longer is
1699 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1700 nullptr);
1701 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001702 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001703 // WM changes displayDevice->layerStack upon sleep/awake.
1704 // Here we make sure we delete the HWC layers even if
1705 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001706 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1707 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001708 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001709 });
1710 }
1711 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1712 displayDevice->undefinedRegion.set(bounds);
1713 displayDevice->undefinedRegion.subtractSelf(
1714 tr.transform(opaqueRegion));
1715 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001716 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001717 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001718}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001719
Romain Guy0147a172017-06-01 13:53:56 -07001720mat4 SurfaceFlinger::computeSaturationMatrix() const {
1721 if (mSaturation == 1.0f) {
1722 return mat4();
1723 }
1724
1725 // Rec.709 luma coefficients
1726 float3 luminance{0.213f, 0.715f, 0.072f};
1727 luminance *= 1.0f - mSaturation;
1728 return mat4(
1729 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1730 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1731 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1732 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1733 );
1734}
1735
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001736// pickColorMode translates a given dataspace into the best available color mode.
1737// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001738android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001739 switch (dataSpace) {
1740 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1741 // system expects.
1742 case HAL_DATASPACE_UNKNOWN:
1743 case HAL_DATASPACE_SRGB:
1744 case HAL_DATASPACE_V0_SRGB:
1745 return HAL_COLOR_MODE_SRGB;
1746 break;
1747
1748 case HAL_DATASPACE_DISPLAY_P3:
1749 return HAL_COLOR_MODE_DISPLAY_P3;
1750 break;
1751
1752 default:
1753 // TODO (courtneygo): Do we want to assert an error here?
1754 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1755 dataSpace);
1756 return HAL_COLOR_MODE_SRGB;
1757 break;
1758 }
1759}
1760
Romain Guy0147a172017-06-01 13:53:56 -07001761android_dataspace SurfaceFlinger::bestTargetDataSpace(
1762 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001763 // Only support sRGB and Display-P3 right now.
1764 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1765 return HAL_DATASPACE_DISPLAY_P3;
1766 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001767 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1768 return HAL_DATASPACE_DISPLAY_P3;
1769 }
1770 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1771 return HAL_DATASPACE_DISPLAY_P3;
1772 }
1773
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001774 return HAL_DATASPACE_V0_SRGB;
1775}
1776
Mathias Agopiancd60f992012-08-16 16:28:27 -07001777void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001778 ATRACE_CALL();
1779 ALOGV("setUpHWComposer");
1780
Jesse Hall028dc8f2013-08-20 16:35:32 -07001781 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001782 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1783 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1784 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1785
1786 // If nothing has changed (!dirty), don't recompose.
1787 // If something changed, but we don't currently have any visible layers,
1788 // and didn't when we last did a composition, then skip it this time.
1789 // The second rule does two things:
1790 // - When all layers are removed from a display, we'll emit one black
1791 // frame, then nothing more until we get new layers.
1792 // - When a display is created with a private layer stack, we won't
1793 // emit any black frames until a layer is added to the layer stack.
1794 bool mustRecompose = dirty && !(empty && wasEmpty);
1795
1796 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1797 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1798 mustRecompose ? "doing" : "skipping",
1799 dirty ? "+" : "-",
1800 empty ? "+" : "-",
1801 wasEmpty ? "+" : "-");
1802
Dan Stoza71433162014-02-04 16:22:36 -08001803 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001804
1805 if (mustRecompose) {
1806 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1807 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001808 }
1809
Dan Stoza9e56aa02015-11-02 13:00:03 -08001810 // build the h/w work list
1811 if (CC_UNLIKELY(mGeometryInvalid)) {
1812 mGeometryInvalid = false;
1813 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1814 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1815 const auto hwcId = displayDevice->getHwcDisplayId();
1816 if (hwcId >= 0) {
1817 const Vector<sp<Layer>>& currentLayers(
1818 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001819 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001820 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001821 if (!layer->hasHwcLayer(hwcId)) {
1822 auto hwcLayer = mHwc->createLayer(hwcId);
1823 if (hwcLayer) {
1824 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1825 } else {
1826 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001827 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001828 }
1829 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001830
Robert Carrae060832016-11-28 10:51:00 -08001831 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001832 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001833 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001834 }
1835 }
1836 }
1837 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001838 }
Riley Andrews03414a12014-07-01 14:22:59 -07001839
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001840
Romain Guy0147a172017-06-01 13:53:56 -07001841 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001842
Dan Stoza9e56aa02015-11-02 13:00:03 -08001843 // Set the per-frame data
1844 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1845 auto& displayDevice = mDisplays[displayId];
1846 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001847
Dan Stoza9e56aa02015-11-02 13:00:03 -08001848 if (hwcId < 0) {
1849 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001850 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001851 if (colorMatrix != mPreviousColorMatrix) {
1852 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1853 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1854 "display %zd: %d", displayId, result);
1855 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001856 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1857 layer->setPerFrameData(displayDevice);
1858 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001859
1860 if (hasWideColorDisplay) {
1861 android_color_mode newColorMode;
1862 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1863
1864 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1865 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1866 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1867 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1868 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1869 }
1870 newColorMode = pickColorMode(newDataSpace);
1871
Romain Guyc53d3552017-07-20 18:49:46 -07001872 // We want the color mode of the boot animation to match that of the bootloader
1873 // To achieve this we suppress color mode changes until after the boot animation
1874 if (mBootFinished) {
1875 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter281e8112017-07-13 17:54:01 -06001876 displayDevice->setCompositionDataSpace(newDataSpace);
Romain Guyc53d3552017-07-20 18:49:46 -07001877 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001878 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001879 }
1880
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001881 mPreviousColorMatrix = colorMatrix;
1882
Dan Stoza9e56aa02015-11-02 13:00:03 -08001883 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001884 auto& displayDevice = mDisplays[displayId];
1885 if (!displayDevice->isDisplayOn()) {
1886 continue;
1887 }
1888
1889 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001890 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1891 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001892 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001893}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001894
Mathias Agopiancd60f992012-08-16 16:28:27 -07001895void SurfaceFlinger::doComposition() {
1896 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 ALOGV("doComposition");
1898
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001899 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001900 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001901 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001902 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001903 // transform the dirty region into this screen's coordinate space
1904 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001905
1906 // repaint the framebuffer (if needed)
1907 doDisplayComposition(hw, dirtyRegion);
1908
Mathias Agopiancd60f992012-08-16 16:28:27 -07001909 hw->dirtyRegion.clear();
1910 hw->flip(hw->swapRegion);
1911 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001912 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001913 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001914 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001915}
1916
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001917void SurfaceFlinger::postFramebuffer()
1918{
Mathias Agopian841cde52012-03-01 15:44:37 -08001919 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001920 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001921
Mathias Agopiana44b0412011-10-16 18:46:35 -07001922 const nsecs_t now = systemTime();
1923 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001924
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1926 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001927 if (!displayDevice->isDisplayOn()) {
1928 continue;
1929 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001930 const auto hwcId = displayDevice->getHwcDisplayId();
1931 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001932 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001933 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001934 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001935 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001936 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1937 sp<Fence> releaseFence = Fence::NO_FENCE;
1938 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1939 releaseFence = displayDevice->getClientTargetAcquireFence();
1940 } else {
1941 auto hwcLayer = layer->getHwcLayer(hwcId);
1942 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001943 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001944 layer->onLayerDisplayed(releaseFence);
1945 }
1946 if (hwcId >= 0) {
1947 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001948 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001949 }
1950
Mathias Agopiana44b0412011-10-16 18:46:35 -07001951 mLastSwapBufferTime = systemTime() - now;
1952 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001953
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001954 // |mStateLock| not needed as we are on the main thread
1955 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001956 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1957 logFrameStats();
1958 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001959}
1960
Mathias Agopian87baae12012-07-31 12:38:26 -07001961void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001962{
Mathias Agopian841cde52012-03-01 15:44:37 -08001963 ATRACE_CALL();
1964
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001965 // here we keep a copy of the drawing state (that is the state that's
1966 // going to be overwritten by handleTransactionLocked()) outside of
1967 // mStateLock so that the side-effects of the State assignment
1968 // don't happen with mStateLock held (which can cause deadlocks).
1969 State drawingState(mDrawingState);
1970
Mathias Agopianca4d3602011-05-19 15:38:14 -07001971 Mutex::Autolock _l(mStateLock);
1972 const nsecs_t now = systemTime();
1973 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001974
Mathias Agopianca4d3602011-05-19 15:38:14 -07001975 // Here we're guaranteed that some transaction flags are set
1976 // so we can call handleTransactionLocked() unconditionally.
1977 // We call getTransactionFlags(), which will also clear the flags,
1978 // with mStateLock held to guarantee that mCurrentState won't change
1979 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001980
Mathias Agopiane57f2922012-08-09 16:29:12 -07001981 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001982 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001983
Mathias Agopianca4d3602011-05-19 15:38:14 -07001984 mLastTransactionTime = systemTime() - now;
1985 mDebugInTransaction = 0;
1986 invalidateHwcGeometry();
1987 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001988}
1989
Mathias Agopian87baae12012-07-31 12:38:26 -07001990void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001991{
Dan Stoza7dde5992015-05-22 09:51:44 -07001992 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001993 mCurrentState.traverseInZOrder([](Layer* layer) {
1994 layer->notifyAvailableFrames();
1995 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001996
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001997 /*
1998 * Traversal of the children
1999 * (perform the transaction for each of them if needed)
2000 */
2001
Mathias Agopian3559b072012-08-15 13:46:03 -07002002 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002003 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002004 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002005 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002006
2007 const uint32_t flags = layer->doTransaction(0);
2008 if (flags & Layer::eVisibleRegion)
2009 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002010 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002011 }
2012
2013 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002014 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002015 */
2016
Mathias Agopiane57f2922012-08-09 16:29:12 -07002017 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002018 // here we take advantage of Vector's copy-on-write semantics to
2019 // improve performance by skipping the transaction entirely when
2020 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002021 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2022 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002023 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002024 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002025 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002026 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002027
2028 // find the displays that were removed
2029 // (ie: in drawing state but not in current state)
2030 // also handle displays that changed
2031 // (ie: displays that are in both lists)
2032 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002033 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2034 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002035 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002036 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002037 // Call makeCurrent() on the primary display so we can
2038 // be sure that nothing associated with this display
2039 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002040 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002041 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002042 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002043 if (hw != NULL)
2044 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002045 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002046 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002047 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002048 } else {
2049 ALOGW("trying to remove the main display");
2050 }
2051 } else {
2052 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002053 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002054 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002055 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2056 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002057 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002058 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002059 // recreating the DisplayDevice, so we just remove it
2060 // from the drawing state, so that it get re-added
2061 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002062 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002063 if (hw != NULL)
2064 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002065 mDisplays.removeItem(display);
2066 mDrawingState.displays.removeItemsAt(i);
2067 dc--; i--;
2068 // at this point we must loop to the next item
2069 continue;
2070 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002071
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002072 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002073 if (disp != NULL) {
2074 if (state.layerStack != draw[i].layerStack) {
2075 disp->setLayerStack(state.layerStack);
2076 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002077 if ((state.orientation != draw[i].orientation)
2078 || (state.viewport != draw[i].viewport)
2079 || (state.frame != draw[i].frame))
2080 {
2081 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002082 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002083 }
Michael Lentine47e45402014-07-18 15:34:25 -07002084 if (state.width != draw[i].width || state.height != draw[i].height) {
2085 disp->setDisplaySize(state.width, state.height);
2086 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002087 }
2088 }
2089 }
2090
2091 // find displays that were added
2092 // (ie: in current state but not in drawing state)
2093 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002094 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002095 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002096
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002097 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002098 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002099 sp<IGraphicBufferProducer> bqProducer;
2100 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002101 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002102
Dan Stoza9e56aa02015-11-02 13:00:03 -08002103 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002104 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002105 // Virtual displays without a surface are dormant:
2106 // they have external state (layer stack, projection,
2107 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002108 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002109
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002110 // Allow VR composer to use virtual displays.
2111 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002112 int width = 0;
2113 int status = state.surface->query(
2114 NATIVE_WINDOW_WIDTH, &width);
2115 ALOGE_IF(status != NO_ERROR,
2116 "Unable to query width (%d)", status);
2117 int height = 0;
2118 status = state.surface->query(
2119 NATIVE_WINDOW_HEIGHT, &height);
2120 ALOGE_IF(status != NO_ERROR,
2121 "Unable to query height (%d)", status);
2122 int intFormat = 0;
2123 status = state.surface->query(
2124 NATIVE_WINDOW_FORMAT, &intFormat);
2125 ALOGE_IF(status != NO_ERROR,
2126 "Unable to query format (%d)", status);
2127 auto format = static_cast<android_pixel_format_t>(
2128 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002129
Dan Stoza8cf150a2016-08-02 10:27:31 -07002130 mHwc->allocateVirtualDisplay(width, height, &format,
2131 &hwcId);
2132 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002133
Dan Stoza5cf424b2016-05-20 14:02:39 -07002134 // TODO: Plumb requested format back up to consumer
2135
Dan Stoza9e56aa02015-11-02 13:00:03 -08002136 sp<VirtualDisplaySurface> vds =
2137 new VirtualDisplaySurface(*mHwc,
2138 hwcId, state.surface, bqProducer,
2139 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002140
2141 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002142 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002143 }
2144 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002145 ALOGE_IF(state.surface!=NULL,
2146 "adding a supported display, but rendering "
2147 "surface is provided (%p), ignoring it",
2148 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002149
2150 hwcId = state.type;
2151 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2152 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002153 }
2154
2155 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002156 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002157 sp<DisplayDevice> hw =
2158 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2159 dispSurface, producer,
2160 mRenderEngine->getEGLConfig(),
2161 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002162 hw->setLayerStack(state.layerStack);
2163 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002164 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002165 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002166 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002167 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002168 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002169 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002170 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002171 }
2172 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002173 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002174 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002175
Mathias Agopian84300952012-11-21 16:02:13 -08002176 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2177 // The transform hint might have changed for some layers
2178 // (either because a display has changed, or because a layer
2179 // as changed).
2180 //
2181 // Walk through all the layers in currentLayers,
2182 // and update their transform hint.
2183 //
2184 // If a layer is visible only on a single display, then that
2185 // display is used to calculate the hint, otherwise we use the
2186 // default display.
2187 //
2188 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2189 // the hint is set before we acquire a buffer from the surface texture.
2190 //
2191 // NOTE: layer transactions have taken place already, so we use their
2192 // drawing state. However, SurfaceFlinger's own transaction has not
2193 // happened yet, so we must use the current state layer list
2194 // (soon to become the drawing state list).
2195 //
2196 sp<const DisplayDevice> disp;
2197 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002198 bool first = true;
2199 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002200 // NOTE: we rely on the fact that layers are sorted by
2201 // layerStack first (so we don't have to traverse the list
2202 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002203 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002204 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002205 currentlayerStack = layerStack;
2206 // figure out if this layerstack is mirrored
2207 // (more than one display) if so, pick the default display,
2208 // if not, pick the only display it's on.
2209 disp.clear();
2210 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2211 sp<const DisplayDevice> hw(mDisplays[dpy]);
2212 if (hw->getLayerStack() == currentlayerStack) {
2213 if (disp == NULL) {
2214 disp = hw;
2215 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002216 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002217 break;
2218 }
2219 }
2220 }
2221 }
Chet Haase91d25932013-04-11 15:24:55 -07002222 if (disp == NULL) {
2223 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2224 // redraw after transform hint changes. See bug 8508397.
2225
2226 // could be null when this layer is using a layerStack
2227 // that is not visible on any display. Also can occur at
2228 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002229 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002230 }
Chet Haase91d25932013-04-11 15:24:55 -07002231 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002232
2233 first = false;
2234 });
Mathias Agopian84300952012-11-21 16:02:13 -08002235 }
2236
2237
Mathias Agopian3559b072012-08-15 13:46:03 -07002238 /*
2239 * Perform our own transaction if needed
2240 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002241
2242 if (mLayersAdded) {
2243 mLayersAdded = false;
2244 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002245 mVisibleRegionsDirty = true;
2246 }
2247
2248 // some layers might have been removed, so
2249 // we need to update the regions they're exposing.
2250 if (mLayersRemoved) {
2251 mLayersRemoved = false;
2252 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002253 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002254 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002255 // this layer is not visible anymore
2256 // TODO: we could traverse the tree from front to back and
2257 // compute the actual visible region
2258 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002259 Region visibleReg;
2260 visibleReg.set(layer->computeScreenBounds());
2261 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002262 }
Robert Carr2047fae2016-11-28 14:09:09 -08002263 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002264 }
2265
2266 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002267
2268 updateCursorAsync();
2269}
2270
2271void SurfaceFlinger::updateCursorAsync()
2272{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002273 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2274 auto& displayDevice = mDisplays[displayId];
2275 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002276 continue;
2277 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002278
2279 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2280 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002281 }
2282 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002283}
2284
2285void SurfaceFlinger::commitTransaction()
2286{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002287 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002288 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002289 for (const auto& l : mLayersPendingRemoval) {
2290 recordBufferingStats(l->getName().string(),
2291 l->getOccupancyHistory(true));
2292 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002293 }
2294 mLayersPendingRemoval.clear();
2295 }
2296
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002297 // If this transaction is part of a window animation then the next frame
2298 // we composite should be considered an animation as well.
2299 mAnimCompositionPending = mAnimTransactionPending;
2300
Mathias Agopian4fec8732012-06-29 14:12:52 -07002301 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002302 mDrawingState.traverseInZOrder([](Layer* layer) {
2303 layer->commitChildList();
2304 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002305 mTransactionPending = false;
2306 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002307 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002308}
2309
Robert Carr2047fae2016-11-28 14:09:09 -08002310void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002311 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002312{
Mathias Agopian841cde52012-03-01 15:44:37 -08002313 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002314 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002315
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002316 Region aboveOpaqueLayers;
2317 Region aboveCoveredLayers;
2318 Region dirty;
2319
Mathias Agopian87baae12012-07-31 12:38:26 -07002320 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002321
Robert Carr2047fae2016-11-28 14:09:09 -08002322 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002323 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002324 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002325
Jesse Hall01e29052013-02-19 16:13:35 -08002326 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002327 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002328 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002329
Mathias Agopianab028732010-03-16 16:41:46 -07002330 /*
2331 * opaqueRegion: area of a surface that is fully opaque.
2332 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002333 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002334
2335 /*
2336 * visibleRegion: area of a surface that is visible on screen
2337 * and not fully transparent. This is essentially the layer's
2338 * footprint minus the opaque regions above it.
2339 * Areas covered by a translucent surface are considered visible.
2340 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002342
2343 /*
2344 * coveredRegion: area of a surface that is covered by all
2345 * visible regions above it (which includes the translucent areas).
2346 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002348
Jesse Halla8026d22012-09-25 13:25:04 -07002349 /*
2350 * transparentRegion: area of a surface that is hinted to be completely
2351 * transparent. This is only used to tell when the layer has no visible
2352 * non-transparent regions and can be removed from the layer list. It
2353 * does not affect the visibleRegion of this layer or any layers
2354 * beneath it. The hint may not be correct if apps don't respect the
2355 * SurfaceView restrictions (which, sadly, some don't).
2356 */
2357 Region transparentRegion;
2358
Mathias Agopianab028732010-03-16 16:41:46 -07002359
2360 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002361 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002362 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002363 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002365 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002366 if (!visibleRegion.isEmpty()) {
2367 // Remove the transparent area from the visible region
2368 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002369 if (tr.preserveRects()) {
2370 // transform the transparent region
2371 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002372 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002373 // transformation too complex, can't do the
2374 // transparent region optimization.
2375 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002376 }
Mathias Agopianab028732010-03-16 16:41:46 -07002377 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002378
Mathias Agopianab028732010-03-16 16:41:46 -07002379 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002380 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002381 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002382 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2383 // the opaque region is the layer's footprint
2384 opaqueRegion = visibleRegion;
2385 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002386 }
2387 }
2388
Mathias Agopianab028732010-03-16 16:41:46 -07002389 // Clip the covered region to the visible region
2390 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2391
2392 // Update aboveCoveredLayers for next (lower) layer
2393 aboveCoveredLayers.orSelf(visibleRegion);
2394
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002395 // subtract the opaque region covered by the layers above us
2396 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002397
2398 // compute this layer's dirty region
2399 if (layer->contentDirty) {
2400 // we need to invalidate the whole region
2401 dirty = visibleRegion;
2402 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002403 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002404 layer->contentDirty = false;
2405 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002406 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002407 * the exposed region consists of two components:
2408 * 1) what's VISIBLE now and was COVERED before
2409 * 2) what's EXPOSED now less what was EXPOSED before
2410 *
2411 * note that (1) is conservative, we start with the whole
2412 * visible region but only keep what used to be covered by
2413 * something -- which mean it may have been exposed.
2414 *
2415 * (2) handles areas that were not covered by anything but got
2416 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002417 */
Mathias Agopianab028732010-03-16 16:41:46 -07002418 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002419 const Region oldVisibleRegion = layer->visibleRegion;
2420 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002421 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2422 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002423 }
2424 dirty.subtractSelf(aboveOpaqueLayers);
2425
2426 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002427 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002428
Mathias Agopianab028732010-03-16 16:41:46 -07002429 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002430 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002431
Jesse Halla8026d22012-09-25 13:25:04 -07002432 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002433 layer->setVisibleRegion(visibleRegion);
2434 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002435 layer->setVisibleNonTransparentRegion(
2436 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002437 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002438
Mathias Agopian87baae12012-07-31 12:38:26 -07002439 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002440}
2441
Mathias Agopian87baae12012-07-31 12:38:26 -07002442void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2443 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002444 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002445 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2446 if (hw->getLayerStack() == layerStack) {
2447 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002448 }
2449 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002450}
2451
Dan Stoza6b9454d2014-11-07 16:00:59 -08002452bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002453{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002454 ALOGV("handlePageFlip");
2455
Brian Andersond6927fb2016-07-23 23:37:30 -07002456 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457
Mathias Agopian4fec8732012-06-29 14:12:52 -07002458 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002459 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002460 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002461
2462 // Store the set of layers that need updates. This set must not change as
2463 // buffers are being latched, as this could result in a deadlock.
2464 // Example: Two producers share the same command stream and:
2465 // 1.) Layer 0 is latched
2466 // 2.) Layer 0 gets a new frame
2467 // 2.) Layer 1 gets a new frame
2468 // 3.) Layer 1 is latched.
2469 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2470 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002471 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002472 if (layer->hasQueuedFrame()) {
2473 frameQueued = true;
2474 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002475 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002476 } else {
2477 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002478 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002479 } else {
2480 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002481 }
Robert Carr2047fae2016-11-28 14:09:09 -08002482 });
2483
Dan Stoza9e56aa02015-11-02 13:00:03 -08002484 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002485 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002486 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002487 invalidateLayerStack(layer->getLayerStack(), dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002488 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002489 newDataLatched = true;
2490 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002491 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002492
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002493 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002494
2495 // If we will need to wake up at some time in the future to deal with a
2496 // queued frame that shouldn't be displayed during this vsync period, wake
2497 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002498 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002499 signalLayerUpdate();
2500 }
2501
2502 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002503 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504}
2505
Mathias Agopianad456f92011-01-13 17:53:01 -08002506void SurfaceFlinger::invalidateHwcGeometry()
2507{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002508 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002509}
2510
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002511
Fabien Sanglard830b8472016-11-30 16:35:58 -08002512void SurfaceFlinger::doDisplayComposition(
2513 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002514 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515{
Dan Stoza71433162014-02-04 16:22:36 -08002516 // We only need to actually compose the display if:
2517 // 1) It is being handled by hardware composer, which may need this to
2518 // keep its virtual display state machine in sync, or
2519 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002520 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002521 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002522 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002523 return;
2524 }
2525
Dan Stoza9e56aa02015-11-02 13:00:03 -08002526 ALOGV("doDisplayComposition");
2527
Mathias Agopian87baae12012-07-31 12:38:26 -07002528 Region dirtyRegion(inDirtyRegion);
2529
Mathias Agopianb8a55602009-06-26 19:06:36 -07002530 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002531 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002532
Fabien Sanglard830b8472016-11-30 16:35:58 -08002533 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002534 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002535 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2536 // takes a rectangle, we must make sure to update that whole
2537 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002538 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002539 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002540 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002541 // We need to redraw the rectangle that will be updated
2542 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002543 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002544 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002545 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002546 } else {
2547 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002548 dirtyRegion.set(displayDevice->bounds());
2549 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002550 }
2551 }
2552
Fabien Sanglard830b8472016-11-30 16:35:58 -08002553 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002555 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002556 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002557
2558 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002559 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002560}
2561
Dan Stoza9e56aa02015-11-02 13:00:03 -08002562bool SurfaceFlinger::doComposeSurfaces(
2563 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002564{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002565 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002566
Dan Stoza9e56aa02015-11-02 13:00:03 -08002567 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002568
2569 mat4 oldColorMatrix;
2570 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2571 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2572 if (applyColorMatrix) {
2573 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2574 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2575 }
2576
Dan Stoza9e56aa02015-11-02 13:00:03 -08002577 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2578 if (hasClientComposition) {
2579 ALOGV("hasClientComposition");
2580
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002581#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002582 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002583 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002584#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002585 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002586 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002587 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002588 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002589
2590 // |mStateLock| not needed as we are on the main thread
2591 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002592 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2593 }
2594 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002595 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002596
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002597 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002598 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2599 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002600 // when using overlays, we assume a fully transparent framebuffer
2601 // NOTE: we could reduce how much we need to clear, for instance
2602 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002603 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002604 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002606 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002607 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002608 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002609
2610 // we remove the scissor part
2611 // we're left with the letterbox region
2612 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002613 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002614
2615 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002616 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002617
2618 // but limit it to the dirty region
2619 region.andSelf(dirty);
2620
Mathias Agopianb9494d52012-04-18 02:28:45 -07002621 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002622 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002623 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002624 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002625 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002626 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002627
Dan Stoza9e56aa02015-11-02 13:00:03 -08002628 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002629 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002630 // scissor on the main display. It should never be needed
2631 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002632 const Rect& bounds(displayDevice->getBounds());
2633 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002634 if (scissor != bounds) {
2635 // scissor doesn't match the screen's dimensions, so we
2636 // need to clear everything outside of it and enable
2637 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002638
Mathias Agopianf45c5102012-10-24 16:29:17 -07002639 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002640 const uint32_t height = displayDevice->getHeight();
2641 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002642 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002643 }
2644 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002645 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002646
Mathias Agopian85d751c2012-08-29 16:59:24 -07002647 /*
2648 * and then, render the layers targeted at the framebuffer
2649 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002650
Dan Stoza9e56aa02015-11-02 13:00:03 -08002651 ALOGV("Rendering client layers");
2652 const Transform& displayTransform = displayDevice->getTransform();
2653 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002654 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002655 bool firstLayer = true;
2656 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2657 const Region clip(dirty.intersect(
2658 displayTransform.transform(layer->visibleRegion)));
2659 ALOGV("Layer: %s", layer->getName().string());
2660 ALOGV(" Composition type: %s",
2661 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002662 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 switch (layer->getCompositionType(hwcId)) {
2664 case HWC2::Composition::Cursor:
2665 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002666 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002667 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002668 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002669 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2670 layer->isOpaque(state) && (state.alpha == 1.0f)
2671 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002672 // never clear the very first layer since we're
2673 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002674 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002675 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002676 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002677 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002678 case HWC2::Composition::Client: {
2679 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002680 break;
2681 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002682 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002683 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002684 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002685 } else {
2686 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002687 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002688 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002689 }
2690 } else {
2691 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002692 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002693 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002694 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002695 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002696 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002697 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002698 }
2699 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002700
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002701 if (applyColorMatrix) {
2702 getRenderEngine().setupColorTransform(oldColorMatrix);
2703 }
2704
Mathias Agopianf45c5102012-10-24 16:29:17 -07002705 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002706 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002707 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708}
2709
Fabien Sanglard830b8472016-11-30 16:35:58 -08002710void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2711 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002712 RenderEngine& engine(getRenderEngine());
2713 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714}
2715
Dan Stoza7d89d062015-04-30 13:29:25 -07002716status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002717 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002718 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002719 const sp<Layer>& lbc,
2720 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002721{
Dan Stoza7d89d062015-04-30 13:29:25 -07002722 // add this layer to the current state list
2723 {
2724 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002725 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002726 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2727 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002728 return NO_MEMORY;
2729 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002730 if (parent == nullptr) {
2731 mCurrentState.layersSortedByZ.add(lbc);
2732 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002733 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2734 ALOGE("addClientLayer called with a removed parent");
2735 return NAME_NOT_FOUND;
2736 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737 parent->addChild(lbc);
2738 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002739
Dan Stoza7d89d062015-04-30 13:29:25 -07002740 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002741 mLayersAdded = true;
2742 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002743 }
2744
Mathias Agopian96f08192010-06-02 23:28:45 -07002745 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002746 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002747
Dan Stoza7d89d062015-04-30 13:29:25 -07002748 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002749}
2750
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002751status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002752 Mutex::Autolock _l(mStateLock);
2753
Robert Carr1f0a16a2016-10-24 16:27:39 -07002754 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002755 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002756 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002757 if (topLevelOnly) {
2758 return NO_ERROR;
2759 }
2760
Chia-I Wu98f1c102017-05-30 14:54:08 -07002761 sp<Layer> ancestor = p;
2762 while (ancestor->getParent() != nullptr) {
2763 ancestor = ancestor->getParent();
2764 }
2765 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2766 ALOGE("removeLayer called with a layer whose parent has been removed");
2767 return NAME_NOT_FOUND;
2768 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002769
2770 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002771 } else {
2772 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002773 }
2774
Robert Carr136e2f62017-02-08 17:54:29 -08002775 // As a matter of normal operation, the LayerCleaner will produce a second
2776 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2777 // so we will succeed in promoting it, but it's already been removed
2778 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2779 // otherwise something has gone wrong and we are leaking the layer.
2780 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002781 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2782 layer->getName().string(),
2783 (p != nullptr) ? p->getName().string() : "no-parent");
2784 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002785 } else if (index < 0) {
2786 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002787 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002788
2789 mLayersPendingRemoval.add(layer);
2790 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002791 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002792 setTransactionFlags(eTransactionNeeded);
2793 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794}
2795
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002796uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002797 return android_atomic_release_load(&mTransactionFlags);
2798}
2799
Mathias Agopian3f844832013-08-07 21:24:32 -07002800uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2802}
2803
Mathias Agopian3f844832013-08-07 21:24:32 -07002804uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002805 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2806 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002807 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808 }
2809 return old;
2810}
2811
Mathias Agopian8b33f032012-07-24 20:43:54 -07002812void SurfaceFlinger::setTransactionState(
2813 const Vector<ComposerState>& state,
2814 const Vector<DisplayState>& displays,
2815 uint32_t flags)
2816{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002817 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002818 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002819 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002820
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002821 if (flags & eAnimation) {
2822 // For window updates that are part of an animation we must wait for
2823 // previous animation "frames" to be handled.
2824 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002825 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002826 if (CC_UNLIKELY(err != NO_ERROR)) {
2827 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002828 // caller after a few seconds.
2829 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2830 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002831 mAnimTransactionPending = false;
2832 break;
2833 }
2834 }
2835 }
2836
Mathias Agopiane57f2922012-08-09 16:29:12 -07002837 size_t count = displays.size();
2838 for (size_t i=0 ; i<count ; i++) {
2839 const DisplayState& s(displays[i]);
2840 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002841 }
2842
Mathias Agopiane57f2922012-08-09 16:29:12 -07002843 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002844 for (size_t i=0 ; i<count ; i++) {
2845 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002846 // Here we need to check that the interface we're given is indeed
2847 // one of our own. A malicious client could give us a NULL
2848 // IInterface, or one of its own or even one of our own but a
2849 // different type. All these situations would cause us to crash.
2850 //
2851 // NOTE: it would be better to use RTTI as we could directly check
2852 // that we have a Client*. however, RTTI is disabled in Android.
2853 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002854 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002855 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002856 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002857 sp<Client> client( static_cast<Client *>(s.client.get()) );
2858 transactionFlags |= setClientStateLocked(client, s.state);
2859 }
2860 }
2861 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002862 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002863
Robert Carr2a7dbb42016-05-24 11:41:28 -07002864 // If a synchronous transaction is explicitly requested without any changes,
2865 // force a transaction anyway. This can be used as a flush mechanism for
2866 // previous async transactions.
2867 if (transactionFlags == 0 && (flags & eSynchronous)) {
2868 transactionFlags = eTransactionNeeded;
2869 }
2870
Mathias Agopian386aa982011-11-07 21:58:03 -08002871 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002872 if (mInterceptor.isEnabled()) {
2873 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2874 }
Irvel468051e2016-06-13 16:44:44 -07002875
Mathias Agopian386aa982011-11-07 21:58:03 -08002876 // this triggers the transaction
2877 setTransactionFlags(transactionFlags);
2878
2879 // if this is a synchronous transaction, wait for it to take effect
2880 // before returning.
2881 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002882 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002883 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002884 if (flags & eAnimation) {
2885 mAnimTransactionPending = true;
2886 }
2887 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002888 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2889 if (CC_UNLIKELY(err != NO_ERROR)) {
2890 // just in case something goes wrong in SF, return to the
2891 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002892 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2893 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002894 break;
2895 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002896 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897 }
2898}
2899
Mathias Agopiane57f2922012-08-09 16:29:12 -07002900uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2901{
Jesse Hall9a143922012-10-04 16:29:19 -07002902 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2903 if (dpyIdx < 0)
2904 return 0;
2905
Mathias Agopiane57f2922012-08-09 16:29:12 -07002906 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002907 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002908 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002909 const uint32_t what = s.what;
2910 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002911 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002912 disp.surface = s.surface;
2913 flags |= eDisplayTransactionNeeded;
2914 }
2915 }
2916 if (what & DisplayState::eLayerStackChanged) {
2917 if (disp.layerStack != s.layerStack) {
2918 disp.layerStack = s.layerStack;
2919 flags |= eDisplayTransactionNeeded;
2920 }
2921 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002922 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002923 if (disp.orientation != s.orientation) {
2924 disp.orientation = s.orientation;
2925 flags |= eDisplayTransactionNeeded;
2926 }
2927 if (disp.frame != s.frame) {
2928 disp.frame = s.frame;
2929 flags |= eDisplayTransactionNeeded;
2930 }
2931 if (disp.viewport != s.viewport) {
2932 disp.viewport = s.viewport;
2933 flags |= eDisplayTransactionNeeded;
2934 }
2935 }
Michael Lentine47e45402014-07-18 15:34:25 -07002936 if (what & DisplayState::eDisplaySizeChanged) {
2937 if (disp.width != s.width) {
2938 disp.width = s.width;
2939 flags |= eDisplayTransactionNeeded;
2940 }
2941 if (disp.height != s.height) {
2942 disp.height = s.height;
2943 flags |= eDisplayTransactionNeeded;
2944 }
2945 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002946 }
2947 return flags;
2948}
2949
2950uint32_t SurfaceFlinger::setClientStateLocked(
2951 const sp<Client>& client,
2952 const layer_state_t& s)
2953{
2954 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002955 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002956 if (layer != 0) {
2957 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002958 bool geometryAppliesWithResize =
2959 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002960 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002961 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002962 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002963 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002964 }
2965 if (what & layer_state_t::eLayerChanged) {
2966 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002967 const auto& p = layer->getParent();
2968 if (p == nullptr) {
2969 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2970 if (layer->setLayer(s.z) && idx >= 0) {
2971 mCurrentState.layersSortedByZ.removeAt(idx);
2972 mCurrentState.layersSortedByZ.add(layer);
2973 // we need traversal (state changed)
2974 // AND transaction (list changed)
2975 flags |= eTransactionNeeded|eTraversalNeeded;
2976 }
2977 } else {
2978 if (p->setChildLayer(layer, s.z)) {
2979 flags |= eTransactionNeeded|eTraversalNeeded;
2980 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002981 }
2982 }
Robert Carrdb66e622017-04-10 16:55:57 -07002983 if (what & layer_state_t::eRelativeLayerChanged) {
2984 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2985 flags |= eTransactionNeeded|eTraversalNeeded;
2986 }
2987 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002988 if (what & layer_state_t::eSizeChanged) {
2989 if (layer->setSize(s.w, s.h)) {
2990 flags |= eTraversalNeeded;
2991 }
2992 }
2993 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002994 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002995 flags |= eTraversalNeeded;
2996 }
2997 if (what & layer_state_t::eMatrixChanged) {
2998 if (layer->setMatrix(s.matrix))
2999 flags |= eTraversalNeeded;
3000 }
3001 if (what & layer_state_t::eTransparentRegionChanged) {
3002 if (layer->setTransparentRegionHint(s.transparentRegion))
3003 flags |= eTraversalNeeded;
3004 }
Dan Stoza23116082015-06-18 14:58:39 -07003005 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003006 if (layer->setFlags(s.flags, s.mask))
3007 flags |= eTraversalNeeded;
3008 }
3009 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003010 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003011 flags |= eTraversalNeeded;
3012 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003013 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003014 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003015 flags |= eTraversalNeeded;
3016 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003017 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003018 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003019 // We only allow setting layer stacks for top level layers,
3020 // everything else inherits layer stack from its parent.
3021 if (layer->hasParent()) {
3022 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3023 layer->getName().string());
3024 } else if (idx < 0) {
3025 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3026 "that also does not appear in the top level layer list. Something"
3027 " has gone wrong.", layer->getName().string());
3028 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003029 mCurrentState.layersSortedByZ.removeAt(idx);
3030 mCurrentState.layersSortedByZ.add(layer);
3031 // we need traversal (state changed)
3032 // AND transaction (list changed)
3033 flags |= eTransactionNeeded|eTraversalNeeded;
3034 }
3035 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003036 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003037 if (s.barrierHandle != nullptr) {
3038 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3039 } else if (s.barrierGbp != nullptr) {
3040 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3041 if (authenticateSurfaceTextureLocked(gbp)) {
3042 const auto& otherLayer =
3043 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3044 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3045 } else {
3046 ALOGE("Attempt to defer transaction to to an"
3047 " unrecognized GraphicBufferProducer");
3048 }
3049 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003050 // We don't trigger a traversal here because if no other state is
3051 // changed, we don't want this to cause any more work
3052 }
Robert Carr1db73f62016-12-21 12:58:51 -08003053 if (what & layer_state_t::eReparentChildren) {
3054 if (layer->reparentChildren(s.reparentHandle)) {
3055 flags |= eTransactionNeeded|eTraversalNeeded;
3056 }
3057 }
Robert Carr9524cb32017-02-13 11:32:32 -08003058 if (what & layer_state_t::eDetachChildren) {
3059 layer->detachChildren();
3060 }
Robert Carrc3574f72016-03-24 12:19:32 -07003061 if (what & layer_state_t::eOverrideScalingModeChanged) {
3062 layer->setOverrideScalingMode(s.overrideScalingMode);
3063 // We don't trigger a traversal here because if no other state is
3064 // changed, we don't want this to cause any more work
3065 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003066 }
3067 return flags;
3068}
3069
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003070status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003071 const String8& name,
3072 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003073 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003074 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3075 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003077 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003078 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003079 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003080 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003081 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003082
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003083 status_t result = NO_ERROR;
3084
3085 sp<Layer> layer;
3086
Cody Northropbc755282017-03-31 12:00:08 -06003087 String8 uniqueName = getUniqueLayerName(name);
3088
Mathias Agopian3165cc22012-08-08 19:42:09 -07003089 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3090 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003091 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003092 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003093 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003095 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003096 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003097 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003098 handle, gbp, &layer);
3099 break;
3100 default:
3101 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102 break;
3103 }
3104
Dan Stoza7d89d062015-04-30 13:29:25 -07003105 if (result != NO_ERROR) {
3106 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003108
Albert Chaulk479c60c2017-01-27 14:21:34 -05003109 layer->setInfo(windowType, ownerUid);
3110
Robert Carr1f0a16a2016-10-24 16:27:39 -07003111 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003112 if (result != NO_ERROR) {
3113 return result;
3114 }
Irvelffc9efc2016-07-27 15:16:37 -07003115 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003116
3117 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003118 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003119}
3120
Cody Northropbc755282017-03-31 12:00:08 -06003121String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3122{
3123 bool matchFound = true;
3124 uint32_t dupeCounter = 0;
3125
3126 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3127 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3128
3129 // Loop over layers until we're sure there is no matching name
3130 while (matchFound) {
3131 matchFound = false;
3132 mDrawingState.traverseInZOrder([&](Layer* layer) {
3133 if (layer->getName() == uniqueName) {
3134 matchFound = true;
3135 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3136 }
3137 });
3138 }
3139
3140 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3141
3142 return uniqueName;
3143}
3144
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003145status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3146 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3147 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148{
3149 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003150 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151 case PIXEL_FORMAT_TRANSPARENT:
3152 case PIXEL_FORMAT_TRANSLUCENT:
3153 format = PIXEL_FORMAT_RGBA_8888;
3154 break;
3155 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003156 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 break;
3158 }
3159
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003160 *outLayer = new Layer(this, client, name, w, h, flags);
3161 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3162 if (err == NO_ERROR) {
3163 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003164 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003166
3167 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3168 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169}
3170
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003171status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3172 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3173 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003175 *outLayer = new LayerDim(this, client, name, w, h, flags);
3176 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003177 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003178 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003179}
3180
Mathias Agopianac9fa422013-02-11 16:40:36 -08003181status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003182{
Robert Carr9524cb32017-02-13 11:32:32 -08003183 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003184 status_t err = NO_ERROR;
3185 sp<Layer> l(client->getLayerUser(handle));
3186 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003187 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003188 err = removeLayer(l);
3189 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3190 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003191 }
3192 return err;
3193}
3194
Mathias Agopian13127d82013-03-05 17:47:11 -08003195status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003196{
Mathias Agopian67106042013-03-14 19:18:13 -07003197 // called by ~LayerCleaner() when all references to the IBinder (handle)
3198 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003199 sp<Layer> l = layer.promote();
3200 if (l == nullptr) {
3201 // The layer has already been removed, carry on
3202 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003203 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003204 // If we have a parent, then we can continue to live as long as it does.
3205 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206}
3207
Mathias Agopianb60314a2012-04-10 22:09:54 -07003208// ---------------------------------------------------------------------------
3209
Andy McFadden13a082e2012-08-24 10:16:42 -07003210void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003211 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003212 Vector<ComposerState> state;
3213 Vector<DisplayState> displays;
3214 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003215 d.what = DisplayState::eDisplayProjectionChanged |
3216 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003217 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003218 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003219 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003220 d.frame.makeInvalid();
3221 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003222 d.width = 0;
3223 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003224 displays.add(d);
3225 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003226 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003227
Dan Stoza9e56aa02015-11-02 13:00:03 -08003228 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3229 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003230 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003231
Brian Andersond0010582017-03-07 13:20:31 -08003232 // Use phase of 0 since phase is not known.
3233 // Use latency of 0, which will snap to the ideal latency.
3234 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003235}
3236
3237void SurfaceFlinger::initializeDisplays() {
3238 class MessageScreenInitialized : public MessageBase {
3239 SurfaceFlinger* flinger;
3240 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003241 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003242 virtual bool handler() {
3243 flinger->onInitializeDisplays();
3244 return true;
3245 }
3246 };
3247 sp<MessageBase> msg = new MessageScreenInitialized(this);
3248 postMessageAsync(msg); // we may be called from main thread, use async message
3249}
3250
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003251void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3252 int mode) {
3253 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3254 this);
3255 int32_t type = hw->getDisplayType();
3256 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003257
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003258 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003259 return;
3260 }
3261
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003262 hw->setPowerMode(mode);
3263 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3264 ALOGW("Trying to set power mode for virtual display");
3265 return;
3266 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003267
Irvelffc9efc2016-07-27 15:16:37 -07003268 if (mInterceptor.isEnabled()) {
3269 Mutex::Autolock _l(mStateLock);
3270 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3271 if (idx < 0) {
3272 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3273 return;
3274 }
3275 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3276 }
3277
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003278 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003279 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003280 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003281 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3282 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003283 // FIXME: eventthread only knows about the main display right now
3284 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003285 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003286 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003287
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003288 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003289 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003290 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003291
3292 struct sched_param param = {0};
3293 param.sched_priority = 1;
3294 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3295 ALOGW("Couldn't set SCHED_FIFO on display on");
3296 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003297 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003298 // Turn off the display
3299 struct sched_param param = {0};
3300 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3301 ALOGW("Couldn't set SCHED_OTHER on display off");
3302 }
3303
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003304 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003305 disableHardwareVsync(true); // also cancels any in-progress resync
3306
Mathias Agopiancde87a32012-09-13 14:09:01 -07003307 // FIXME: eventthread only knows about the main display right now
3308 mEventThread->onScreenReleased();
3309 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003310
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003311 getHwComposer().setPowerMode(type, mode);
3312 mVisibleRegionsDirty = true;
3313 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003314 } else if (mode == HWC_POWER_MODE_DOZE ||
3315 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003316 // Update display while dozing
3317 getHwComposer().setPowerMode(type, mode);
3318 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3319 // FIXME: eventthread only knows about the main display right now
3320 mEventThread->onScreenAcquired();
3321 resyncToHardwareVsync(true);
3322 }
3323 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3324 // Leave display going to doze
3325 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3326 disableHardwareVsync(true); // also cancels any in-progress resync
3327 // FIXME: eventthread only knows about the main display right now
3328 mEventThread->onScreenReleased();
3329 }
3330 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003331 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003332 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003333 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003334 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003335}
3336
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003337void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3338 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003339 SurfaceFlinger& mFlinger;
3340 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003341 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003342 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003343 MessageSetPowerMode(SurfaceFlinger& flinger,
3344 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3345 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003346 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003347 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003348 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003349 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003350 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003351 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003352 ALOGW("Attempt to set power mode = %d for virtual display",
3353 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003354 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003355 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003356 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003357 return true;
3358 }
3359 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003360 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003361 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003362}
3363
3364// ---------------------------------------------------------------------------
3365
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3367{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003368 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003369
Mathias Agopianbd115332013-04-18 16:41:04 -07003370 IPCThreadState* ipc = IPCThreadState::self();
3371 const int pid = ipc->getCallingPid();
3372 const int uid = ipc->getCallingUid();
3373 if ((uid != AID_SHELL) &&
3374 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003375 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003376 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003377 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003378 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003379 // (this would indicate SF is stuck, but we want to be able to
3380 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003381 status_t err = mStateLock.timedLock(s2ns(1));
3382 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003383 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003384 result.appendFormat(
3385 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3386 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003387 }
3388
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003389 bool dumpAll = true;
3390 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003391 size_t numArgs = args.size();
3392 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003393 if ((index < numArgs) &&
3394 (args[index] == String16("--list"))) {
3395 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003396 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003397 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003398 }
3399
3400 if ((index < numArgs) &&
3401 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003402 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003403 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003404 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003405 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003406
3407 if ((index < numArgs) &&
3408 (args[index] == String16("--latency-clear"))) {
3409 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003410 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003411 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003412 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003413
3414 if ((index < numArgs) &&
3415 (args[index] == String16("--dispsync"))) {
3416 index++;
3417 mPrimaryDispSync.dump(result);
3418 dumpAll = false;
3419 }
Dan Stozab90cf072015-03-05 11:05:59 -08003420
3421 if ((index < numArgs) &&
3422 (args[index] == String16("--static-screen"))) {
3423 index++;
3424 dumpStaticScreenStats(result);
3425 dumpAll = false;
3426 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003427
3428 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003429 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003430 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003431 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003432 dumpAll = false;
3433 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003434
3435 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3436 index++;
3437 dumpWideColorInfo(result);
3438 dumpAll = false;
3439 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003440 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003441
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003442 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003443 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003444 }
3445
Mathias Agopian9795c422009-08-26 16:36:26 -07003446 if (locked) {
3447 mStateLock.unlock();
3448 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003449 }
3450 write(fd, result.string(), result.size());
3451 return NO_ERROR;
3452}
3453
Dan Stozac7014012014-02-14 15:03:43 -08003454void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3455 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003456{
Robert Carr2047fae2016-11-28 14:09:09 -08003457 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003458 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003459 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003460}
3461
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003462void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003463 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003464{
3465 String8 name;
3466 if (index < args.size()) {
3467 name = String8(args[index]);
3468 index++;
3469 }
3470
Dan Stoza9e56aa02015-11-02 13:00:03 -08003471 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3472 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003473 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003474
3475 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003476 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003477 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003478 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003479 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003480 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003481 }
Robert Carr2047fae2016-11-28 14:09:09 -08003482 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003483 }
3484}
3485
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003486void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003487 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003488{
3489 String8 name;
3490 if (index < args.size()) {
3491 name = String8(args[index]);
3492 index++;
3493 }
3494
Robert Carr2047fae2016-11-28 14:09:09 -08003495 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003496 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003497 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003498 }
Robert Carr2047fae2016-11-28 14:09:09 -08003499 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003500
Svetoslavd85084b2014-03-20 10:28:31 -07003501 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003502}
3503
Jamie Gennis6547ff42013-07-16 20:12:42 -07003504// This should only be called from the main thread. Otherwise it would need
3505// the lock and should use mCurrentState rather than mDrawingState.
3506void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003507 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003508 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003509 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003510
3511 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3512}
3513
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003514void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003515{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003516 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003517 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3518
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003519 if (isLayerTripleBufferingDisabled())
3520 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003521
3522 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003523 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003524 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003525 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003526 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3527 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003528 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003529}
3530
Dan Stozab90cf072015-03-05 11:05:59 -08003531void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3532{
3533 result.appendFormat("Static screen stats:\n");
3534 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3535 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3536 float percent = 100.0f *
3537 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3538 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3539 b + 1, bucketTimeSec, percent);
3540 }
3541 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3542 float percent = 100.0f *
3543 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3544 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3545 NUM_BUCKETS - 1, bucketTimeSec, percent);
3546}
3547
Dan Stozae77c7662016-05-13 11:37:28 -07003548void SurfaceFlinger::recordBufferingStats(const char* layerName,
3549 std::vector<OccupancyTracker::Segment>&& history) {
3550 Mutex::Autolock lock(mBufferingStatsMutex);
3551 auto& stats = mBufferingStats[layerName];
3552 for (const auto& segment : history) {
3553 if (!segment.usedThirdBuffer) {
3554 stats.twoBufferTime += segment.totalTime;
3555 }
3556 if (segment.occupancyAverage < 1.0f) {
3557 stats.doubleBufferedTime += segment.totalTime;
3558 } else if (segment.occupancyAverage < 2.0f) {
3559 stats.tripleBufferedTime += segment.totalTime;
3560 }
3561 ++stats.numSegments;
3562 stats.totalTime += segment.totalTime;
3563 }
3564}
3565
Brian Andersond6927fb2016-07-23 23:37:30 -07003566void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3567 result.appendFormat("Layer frame timestamps:\n");
3568
3569 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3570 const size_t count = currentLayers.size();
3571 for (size_t i=0 ; i<count ; i++) {
3572 currentLayers[i]->dumpFrameEvents(result);
3573 }
3574}
3575
Dan Stozae77c7662016-05-13 11:37:28 -07003576void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3577 result.append("Buffering stats:\n");
3578 result.append(" [Layer name] <Active time> <Two buffer> "
3579 "<Double buffered> <Triple buffered>\n");
3580 Mutex::Autolock lock(mBufferingStatsMutex);
3581 typedef std::tuple<std::string, float, float, float> BufferTuple;
3582 std::map<float, BufferTuple, std::greater<float>> sorted;
3583 for (const auto& statsPair : mBufferingStats) {
3584 const char* name = statsPair.first.c_str();
3585 const BufferingStats& stats = statsPair.second;
3586 if (stats.numSegments == 0) {
3587 continue;
3588 }
3589 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3590 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3591 stats.totalTime;
3592 float doubleBufferRatio = static_cast<float>(
3593 stats.doubleBufferedTime) / stats.totalTime;
3594 float tripleBufferRatio = static_cast<float>(
3595 stats.tripleBufferedTime) / stats.totalTime;
3596 sorted.insert({activeTime, {name, twoBufferRatio,
3597 doubleBufferRatio, tripleBufferRatio}});
3598 }
3599 for (const auto& sortedPair : sorted) {
3600 float activeTime = sortedPair.first;
3601 const BufferTuple& values = sortedPair.second;
3602 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3603 std::get<0>(values).c_str(), activeTime,
3604 std::get<1>(values), std::get<2>(values),
3605 std::get<3>(values));
3606 }
3607 result.append("\n");
3608}
3609
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003610void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3611 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3612
3613 // TODO: print out if wide-color mode is active or not
3614
3615 for (size_t d = 0; d < mDisplays.size(); d++) {
3616 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3617 int32_t hwcId = displayDevice->getHwcDisplayId();
3618 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3619 continue;
3620 }
3621
3622 result.appendFormat("Display %d color modes:\n", hwcId);
3623 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3624 for (auto&& mode : modes) {
3625 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3626 }
3627
3628 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3629 result.appendFormat(" Current color mode: %s (%d)\n",
3630 decodeColorMode(currentMode).c_str(), currentMode);
3631 }
3632 result.append("\n");
3633}
3634
Mathias Agopian74d211a2013-04-22 16:55:35 +02003635void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3636 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003637{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003638 bool colorize = false;
3639 if (index < args.size()
3640 && (args[index] == String16("--color"))) {
3641 colorize = true;
3642 index++;
3643 }
3644
3645 Colorizer colorizer(colorize);
3646
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003647 // figure out if we're stuck somewhere
3648 const nsecs_t now = systemTime();
3649 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3650 const nsecs_t inTransaction(mDebugInTransaction);
3651 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3652 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3653
3654 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003655 * Dump library configuration.
3656 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003657
3658 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003659 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003660 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003661 appendSfConfigString(result);
3662 appendUiConfigString(result);
3663 appendGuiConfigString(result);
3664 result.append("\n");
3665
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003666 result.append("\nWide-Color information:\n");
3667 dumpWideColorInfo(result);
3668
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003669 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003670 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003671 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003672 result.append(SyncFeatures::getInstance().toString());
3673 result.append("\n");
3674
Dan Stoza9e56aa02015-11-02 13:00:03 -08003675 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3676
Andy McFadden41d67d72014-04-25 16:58:34 -07003677 colorizer.bold(result);
3678 result.append("DispSync configuration: ");
3679 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003680 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003681 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003682 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003683 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003684 result.append("\n");
3685
Dan Stozab90cf072015-03-05 11:05:59 -08003686 // Dump static screen stats
3687 result.append("\n");
3688 dumpStaticScreenStats(result);
3689 result.append("\n");
3690
Dan Stozae77c7662016-05-13 11:37:28 -07003691 dumpBufferingStats(result);
3692
Andy McFadden4803b742012-09-24 19:07:20 -07003693 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003694 * Dump the visible layer list
3695 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003696 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003697 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003698 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003699 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003700 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003701 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003702
3703 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003704 * Dump Display state
3705 */
3706
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003707 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003708 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003709 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003710 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3711 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003712 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003713 }
3714
3715 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003716 * Dump SurfaceFlinger global state
3717 */
3718
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003719 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003720 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003721 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003722
Mathias Agopian888c8222012-08-04 21:10:38 -07003723 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003724 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003725
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003726 colorizer.bold(result);
3727 result.appendFormat("EGL implementation : %s\n",
3728 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3729 colorizer.reset(result);
3730 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003731 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003732
Mathias Agopian875d8e12013-06-07 15:35:48 -07003733 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003734
Mathias Agopian42977342012-08-05 00:40:46 -07003735 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003736 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3737 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003738 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003739 " last eglSwapBuffers() time: %f us\n"
3740 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003741 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003742 " refresh-rate : %f fps\n"
3743 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003744 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003745 " gpu_to_cpu_unsupported : %d\n"
3746 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003747 mLastSwapBufferTime/1000.0,
3748 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003749 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003750 1e9 / activeConfig->getVsyncPeriod(),
3751 activeConfig->getDpiX(),
3752 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003753 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003754
Mathias Agopian74d211a2013-04-22 16:55:35 +02003755 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003756 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003757
Mathias Agopian74d211a2013-04-22 16:55:35 +02003758 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003759 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003760
3761 /*
3762 * VSYNC state
3763 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003764 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003765 result.append("\n");
3766
3767 /*
3768 * HWC layer minidump
3769 */
3770 for (size_t d = 0; d < mDisplays.size(); d++) {
3771 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3772 int32_t hwcId = displayDevice->getHwcDisplayId();
3773 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3774 continue;
3775 }
3776
3777 result.appendFormat("Display %d HWC layers:\n", hwcId);
3778 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003779 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003780 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003781 });
Dan Stozae22aec72016-08-01 13:20:59 -07003782 result.append("\n");
3783 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003784
3785 /*
3786 * Dump HWComposer state
3787 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003788 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003789 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003790 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003791 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003792 result.appendFormat(" h/w composer %s\n",
3793 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003794 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003795
3796 /*
3797 * Dump gralloc state
3798 */
3799 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3800 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003801
3802 /*
3803 * Dump VrFlinger state if in use.
3804 */
3805 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3806 result.append("VrFlinger state:\n");
3807 result.append(mVrFlinger->Dump().c_str());
3808 result.append("\n");
3809 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003810}
3811
Mathias Agopian13127d82013-03-05 17:47:11 -08003812const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003813SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003814 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003815 wp<IBinder> dpy;
3816 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3817 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3818 dpy = mDisplays.keyAt(i);
3819 break;
3820 }
3821 }
3822 if (dpy == NULL) {
3823 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3824 // Just use the primary display so we have something to return
3825 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3826 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003827 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003828}
3829
Keun young Park63f165f2012-08-31 10:53:36 -07003830bool SurfaceFlinger::startDdmConnection()
3831{
3832 void* libddmconnection_dso =
3833 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3834 if (!libddmconnection_dso) {
3835 return false;
3836 }
3837 void (*DdmConnection_start)(const char* name);
3838 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003839 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003840 if (!DdmConnection_start) {
3841 dlclose(libddmconnection_dso);
3842 return false;
3843 }
3844 (*DdmConnection_start)(getServiceName());
3845 return true;
3846}
3847
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003848status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003849 switch (code) {
3850 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003851 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003852 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003853 case CLEAR_ANIMATION_FRAME_STATS:
3854 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003855 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003856 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003857 {
3858 // codes that require permission check
3859 IPCThreadState* ipc = IPCThreadState::self();
3860 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003861 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003862 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003863 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003864 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003865 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003866 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003867 break;
3868 }
Robert Carr1db73f62016-12-21 12:58:51 -08003869 /*
3870 * Calling setTransactionState is safe, because you need to have been
3871 * granted a reference to Client* and Handle* to do anything with it.
3872 *
3873 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3874 */
3875 case SET_TRANSACTION_STATE:
3876 case CREATE_SCOPED_CONNECTION:
3877 {
3878 return OK;
3879 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003880 case CAPTURE_SCREEN:
3881 {
3882 // codes that require permission check
3883 IPCThreadState* ipc = IPCThreadState::self();
3884 const int pid = ipc->getCallingPid();
3885 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003886 if ((uid != AID_GRAPHICS) &&
3887 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003888 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003889 return PERMISSION_DENIED;
3890 }
3891 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003892 }
3893 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003894 return OK;
3895}
3896
3897status_t SurfaceFlinger::onTransact(
3898 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3899{
3900 status_t credentialCheck = CheckTransactCodeCredentials(code);
3901 if (credentialCheck != OK) {
3902 return credentialCheck;
3903 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003904
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003905 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3906 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003907 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003908 IPCThreadState* ipc = IPCThreadState::self();
3909 const int uid = ipc->getCallingUid();
3910 if (CC_UNLIKELY(uid != AID_SYSTEM
3911 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003912 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003913 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003914 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003915 return PERMISSION_DENIED;
3916 }
3917 int n;
3918 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003919 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003920 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003921 return NO_ERROR;
3922 case 1002: // SHOW_UPDATES
3923 n = data.readInt32();
3924 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003925 invalidateHwcGeometry();
3926 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003927 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003929 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003930 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003931 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003932 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003933 setTransactionFlags(
3934 eTransactionNeeded|
3935 eDisplayTransactionNeeded|
3936 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003937 return NO_ERROR;
3938 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003939 case 1006:{ // send empty update
3940 signalRefresh();
3941 return NO_ERROR;
3942 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003943 case 1008: // toggle use of hw composer
3944 n = data.readInt32();
3945 mDebugDisableHWC = n ? 1 : 0;
3946 invalidateHwcGeometry();
3947 repaintEverything();
3948 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003949 case 1009: // toggle use of transform hint
3950 n = data.readInt32();
3951 mDebugDisableTransformHint = n ? 1 : 0;
3952 invalidateHwcGeometry();
3953 repaintEverything();
3954 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003955 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003956 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003957 reply->writeInt32(0);
3958 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003959 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003960 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003961 return NO_ERROR;
3962 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003963 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003964 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003965 return NO_ERROR;
3966 }
3967 case 1014: {
3968 // daltonize
3969 n = data.readInt32();
3970 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003971 case 1:
3972 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3973 break;
3974 case 2:
3975 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3976 break;
3977 case 3:
3978 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3979 break;
3980 default:
3981 mDaltonizer.setType(ColorBlindnessType::None);
3982 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003983 }
3984 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003985 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003986 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003987 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003988 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003989 invalidateHwcGeometry();
3990 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003991 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003992 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003993 case 1015: {
3994 // apply a color matrix
3995 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003996 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07003997 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07003998 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003999 for (size_t j = 0; j < 4; j++) {
4000 mColorMatrix[i][j] = data.readFloat();
4001 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004002 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004003 } else {
4004 mColorMatrix = mat4();
4005 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004006
4007 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4008 // the division by w in the fragment shader
4009 float4 lastRow(transpose(mColorMatrix)[3]);
4010 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4011 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4012 }
4013
Alan Viverette9c5a3332013-09-12 20:04:35 -07004014 invalidateHwcGeometry();
4015 repaintEverything();
4016 return NO_ERROR;
4017 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004018 // This is an experimental interface
4019 // Needs to be shifted to proper binder interface when we productize
4020 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004021 n = data.readInt32();
4022 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004023 return NO_ERROR;
4024 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004025 case 1017: {
4026 n = data.readInt32();
4027 mForceFullDamage = static_cast<bool>(n);
4028 return NO_ERROR;
4029 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004030 case 1018: { // Modify Choreographer's phase offset
4031 n = data.readInt32();
4032 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4033 return NO_ERROR;
4034 }
4035 case 1019: { // Modify SurfaceFlinger's phase offset
4036 n = data.readInt32();
4037 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4038 return NO_ERROR;
4039 }
Irvel468051e2016-06-13 16:44:44 -07004040 case 1020: { // Layer updates interceptor
4041 n = data.readInt32();
4042 if (n) {
4043 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004044 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004045 }
4046 else{
4047 ALOGV("Interceptor disabled");
4048 mInterceptor.disable();
4049 }
4050 return NO_ERROR;
4051 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004052 case 1021: { // Disable HWC virtual displays
4053 n = data.readInt32();
4054 mUseHwcVirtualDisplays = !n;
4055 return NO_ERROR;
4056 }
Romain Guy0147a172017-06-01 13:53:56 -07004057 case 1022: { // Set saturation boost
4058 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4059
4060 invalidateHwcGeometry();
4061 repaintEverything();
4062 return NO_ERROR;
4063 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004064 }
4065 }
4066 return err;
4067}
4068
Mathias Agopian53331da2011-08-22 21:44:41 -07004069void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004070 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004071 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004072}
4073
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004074// Checks that the requested width and height are valid and updates them to the display dimensions
4075// if they are set to 0
4076static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4077 Transform::orientation_flags rotation,
4078 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4079 // get screen geometry
4080 uint32_t displayWidth = displayDevice->getWidth();
4081 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004082
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004083 if (rotation & Transform::ROT_90) {
4084 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004085 }
4086
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004087 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4088 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4089 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4090 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004091 }
4092
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004093 if (*requestedWidth == 0) {
4094 *requestedWidth = displayWidth;
4095 }
4096 if (*requestedHeight == 0) {
4097 *requestedHeight = displayHeight;
4098 }
4099
4100 return NO_ERROR;
4101}
4102
4103// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4104class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004105public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004106 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4107 ~WindowDisconnector() {
4108 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004109 }
4110
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004111private:
4112 ANativeWindow* mWindow;
4113 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004114};
4115
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004116static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4117 uint32_t requestedHeight, bool hasWideColorDisplay,
4118 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4119 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4120 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4121
4122 int err = 0;
4123 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4124 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4125 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4126 err |= native_window_set_usage(window, usage);
4127
4128 if (hasWideColorDisplay) {
4129 err |= native_window_set_buffers_data_space(window,
4130 renderEngineUsesWideColor
4131 ? HAL_DATASPACE_DISPLAY_P3
4132 : HAL_DATASPACE_V0_SRGB);
4133 }
4134
4135 if (err != NO_ERROR) {
4136 return BAD_VALUE;
4137 }
4138
4139 /* TODO: Once we have the sync framework everywhere this can use
4140 * server-side waits on the fence that dequeueBuffer returns.
4141 */
4142 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4143 if (err != NO_ERROR) {
4144 return err;
4145 }
4146
4147 return NO_ERROR;
4148}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004149
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004150status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4151 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004152 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004153 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004154 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004155 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004156
4157 if (CC_UNLIKELY(display == 0))
4158 return BAD_VALUE;
4159
4160 if (CC_UNLIKELY(producer == 0))
4161 return BAD_VALUE;
4162
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004163 // if we have secure windows on this display, never allow the screen capture
4164 // unless the producer interface is local (i.e.: we can take a screenshot for
4165 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004166 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004167
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004168 // Convert to surfaceflinger's internal rotation type.
4169 Transform::orientation_flags rotationFlags;
4170 switch (rotation) {
4171 case ISurfaceComposer::eRotateNone:
4172 rotationFlags = Transform::ROT_0;
4173 break;
4174 case ISurfaceComposer::eRotate90:
4175 rotationFlags = Transform::ROT_90;
4176 break;
4177 case ISurfaceComposer::eRotate180:
4178 rotationFlags = Transform::ROT_180;
4179 break;
4180 case ISurfaceComposer::eRotate270:
4181 rotationFlags = Transform::ROT_270;
4182 break;
4183 default:
4184 rotationFlags = Transform::ROT_0;
4185 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4186 break;
4187 }
4188
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004189 { // Autolock scope
4190 Mutex::Autolock lock(mStateLock);
4191 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4192 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004193 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004194
4195 // create a surface (because we're a producer, and we need to
4196 // dequeue/queue a buffer)
4197 sp<Surface> surface = new Surface(producer, false);
4198
4199 // Put the screenshot Surface into async mode so that
4200 // Layer::headFenceHasSignaled will always return true and we'll latch the
4201 // first buffer regardless of whether or not its acquire fence has
4202 // signaled. This is needed to avoid a race condition in the rotation
4203 // animation. See b/30209608
4204 surface->setAsyncMode(true);
4205
4206 ANativeWindow* window = surface.get();
4207
4208 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4209 if (result != NO_ERROR) {
4210 return result;
4211 }
4212 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4213
4214 ANativeWindowBuffer* buffer = nullptr;
4215 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4216 getRenderEngine().usesWideColor(), &buffer);
4217 if (result != NO_ERROR) {
4218 return result;
4219 }
4220
4221 // This mutex protects syncFd and captureResult for communication of the return values from the
4222 // main thread back to this Binder thread
4223 std::mutex captureMutex;
4224 std::condition_variable captureCondition;
4225 std::unique_lock<std::mutex> captureLock(captureMutex);
4226 int syncFd = -1;
4227 std::optional<status_t> captureResult;
4228
4229 sp<LambdaMessage> message = new LambdaMessage([&]() {
4230 // If there is a refresh pending, bug out early and tell the binder thread to try again
4231 // after the refresh.
4232 if (mRefreshPending) {
4233 ATRACE_NAME("Skipping screenshot for now");
4234 std::unique_lock<std::mutex> captureLock(captureMutex);
4235 captureResult = std::make_optional<status_t>(EAGAIN);
4236 captureCondition.notify_one();
4237 return;
4238 }
4239
4240 status_t result = NO_ERROR;
4241 int fd = -1;
4242 {
4243 Mutex::Autolock _l(mStateLock);
4244 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4245 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4246 minLayerZ, maxLayerZ, useIdentityTransform,
4247 rotationFlags, isLocalScreenshot, &fd);
4248 }
4249
4250 {
4251 std::unique_lock<std::mutex> captureLock(captureMutex);
4252 syncFd = fd;
4253 captureResult = std::make_optional<status_t>(result);
4254 captureCondition.notify_one();
4255 }
4256 });
4257
4258 result = postMessageAsync(message);
4259 if (result == NO_ERROR) {
4260 captureCondition.wait(captureLock, [&]() { return captureResult; });
4261 while (*captureResult == EAGAIN) {
4262 captureResult.reset();
4263 result = postMessageAsync(message);
4264 if (result != NO_ERROR) {
4265 return result;
4266 }
4267 captureCondition.wait(captureLock, [&]() { return captureResult; });
4268 }
4269 result = *captureResult;
4270 }
4271
4272 if (result == NO_ERROR) {
4273 // queueBuffer takes ownership of syncFd
4274 result = window->queueBuffer(window, buffer, syncFd);
4275 }
4276
4277 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004278}
4279
Mathias Agopian180f10d2013-04-10 22:55:41 -07004280
4281void SurfaceFlinger::renderScreenImplLocked(
4282 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004283 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004284 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004285 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004286{
4287 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004288 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004289
4290 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004291 const int32_t hw_w = hw->getWidth();
4292 const int32_t hw_h = hw->getHeight();
4293 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004294 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004295
Dan Stozac1879002014-05-22 15:59:05 -07004296 // if a default or invalid sourceCrop is passed in, set reasonable values
4297 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4298 !sourceCrop.isValid()) {
4299 sourceCrop.setLeftTop(Point(0, 0));
4300 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4301 }
4302
4303 // ensure that sourceCrop is inside screen
4304 if (sourceCrop.left < 0) {
4305 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4306 }
Dan Stozabe31f442014-06-11 11:20:54 -07004307 if (sourceCrop.right > hw_w) {
4308 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004309 }
4310 if (sourceCrop.top < 0) {
4311 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4312 }
Dan Stozabe31f442014-06-11 11:20:54 -07004313 if (sourceCrop.bottom > hw_h) {
4314 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004315 }
4316
Romain Guy88d37dd2017-05-26 17:57:05 -07004317#ifdef USE_HWC2
4318 engine.setWideColor(hw->getWideColorSupport());
4319 engine.setColorMode(hw->getActiveColorMode());
4320#endif
4321
Mathias Agopian180f10d2013-04-10 22:55:41 -07004322 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004323 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004324
4325 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004326 engine.setViewportAndProjection(
4327 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004328 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004329
4330 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004331 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004332
Robert Carr1f0a16a2016-10-24 16:27:39 -07004333 // We loop through the first level of layers without traversing,
4334 // as we need to interpret min/max layer Z in the top level Z space.
4335 for (const auto& layer : mDrawingState.layersSortedByZ) {
4336 if (layer->getLayerStack() != hw->getLayerStack()) {
4337 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004338 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004339 const Layer::State& state(layer->getDrawingState());
4340 if (state.z < minLayerZ || state.z > maxLayerZ) {
4341 continue;
4342 }
Dan Stoza412903f2017-04-27 13:42:17 -07004343 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004344 if (!layer->isVisible()) {
4345 return;
4346 }
4347 if (filtering) layer->setFiltering(true);
4348 layer->draw(hw, useIdentityTransform);
4349 if (filtering) layer->setFiltering(false);
4350 });
4351 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004352
Mathias Agopian931bda12013-08-28 18:11:46 -07004353 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004354}
4355
Dan Stozaabcda352017-06-01 14:37:39 -07004356// A simple RAII class that holds an EGLImage and destroys it either:
4357// a) When the destroy() method is called
4358// b) When the object goes out of scope
4359class ImageHolder {
4360public:
4361 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4362 ~ImageHolder() { destroy(); }
4363
4364 void destroy() {
4365 if (mImage != EGL_NO_IMAGE_KHR) {
4366 eglDestroyImageKHR(mDisplay, mImage);
4367 mImage = EGL_NO_IMAGE_KHR;
4368 }
4369 }
4370
4371private:
4372 const EGLDisplay mDisplay;
4373 EGLImageKHR mImage;
4374};
4375
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004376status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4377 ANativeWindowBuffer* buffer, Rect sourceCrop,
4378 uint32_t reqWidth, uint32_t reqHeight,
4379 int32_t minLayerZ, int32_t maxLayerZ,
4380 bool useIdentityTransform,
4381 Transform::orientation_flags rotation,
4382 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004383 ATRACE_CALL();
4384
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004385 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004386 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004387 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004388 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4389 (state.z < minLayerZ || state.z > maxLayerZ)) {
4390 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004391 }
Dan Stoza412903f2017-04-27 13:42:17 -07004392 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004393 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4394 layer->isSecure());
4395 });
4396 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004397
4398 if (!isLocalScreenshot && secureLayerIsVisible) {
4399 ALOGW("FB is protected: PERMISSION_DENIED");
4400 return PERMISSION_DENIED;
4401 }
4402
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004403 int syncFd = -1;
4404 // create an EGLImage from the buffer so we can later
4405 // turn it into a texture
4406 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4407 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4408 if (image == EGL_NO_IMAGE_KHR) {
4409 return BAD_VALUE;
4410 }
4411
Dan Stozaabcda352017-06-01 14:37:39 -07004412 // This will automatically destroy the image if we return before calling its destroy method
4413 ImageHolder imageHolder(mEGLDisplay, image);
4414
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004415 // this binds the given EGLImage as a framebuffer for the
4416 // duration of this scope.
4417 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004418 if (imageBond.getStatus() != NO_ERROR) {
4419 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004420 return INVALID_OPERATION;
4421 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004422
Dan Stozaabcda352017-06-01 14:37:39 -07004423 // this will in fact render into our dequeued buffer
4424 // via an FBO, which means we didn't have to create
4425 // an EGLSurface and therefore we're not
4426 // dependent on the context's EGLConfig.
4427 renderScreenImplLocked(
4428 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4429 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004430
Dan Stozaabcda352017-06-01 14:37:39 -07004431 // Attempt to create a sync khr object that can produce a sync point. If that
4432 // isn't available, create a non-dupable sync object in the fallback path and
4433 // wait on it directly.
4434 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4435 if (!DEBUG_SCREENSHOTS) {
4436 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4437 // native fence fd will not be populated until flush() is done.
4438 getRenderEngine().flush();
4439 }
4440
4441 if (sync != EGL_NO_SYNC_KHR) {
4442 // get the sync fd
4443 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4444 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4445 ALOGW("captureScreen: failed to dup sync khr object");
4446 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004447 }
Dan Stozaabcda352017-06-01 14:37:39 -07004448 eglDestroySyncKHR(mEGLDisplay, sync);
4449 } else {
4450 // fallback path
4451 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004452 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004453 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4454 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4455 EGLint eglErr = eglGetError();
4456 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4457 ALOGW("captureScreen: fence wait timed out");
4458 } else {
4459 ALOGW_IF(eglErr != EGL_SUCCESS,
4460 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004461 }
4462 eglDestroySyncKHR(mEGLDisplay, sync);
4463 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004464 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004465 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004466 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004467 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004468
4469 if (DEBUG_SCREENSHOTS) {
4470 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4471 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4472 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4473 hw, minLayerZ, maxLayerZ);
4474 delete [] pixels;
4475 }
4476
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004477 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004478 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004479
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004480 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004481}
4482
Mathias Agopiand5556842013-09-19 17:08:37 -07004483void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004484 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004485 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004486 for (size_t y=0 ; y<h ; y++) {
4487 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4488 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004489 if (p[x] != 0xFF000000) return;
4490 }
4491 }
4492 ALOGE("*** we just took a black screenshot ***\n"
4493 "requested minz=%d, maxz=%d, layerStack=%d",
4494 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004495
Robert Carr2047fae2016-11-28 14:09:09 -08004496 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004497 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004498 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004499 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4500 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004501 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004502 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4503 layer->isVisible() ? '+' : '-',
4504 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004505 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004506 i++;
4507 });
4508 }
4509 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004510 }
4511}
4512
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004513// ---------------------------------------------------------------------------
4514
Dan Stoza412903f2017-04-27 13:42:17 -07004515void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4516 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004517}
4518
Dan Stoza412903f2017-04-27 13:42:17 -07004519void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4520 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004521}
4522
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004523}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004524
4525
4526#if defined(__gl_h_)
4527#error "don't include gl/gl.h in this file"
4528#endif
4529
4530#if defined(__gl2_h_)
4531#error "don't include gl2/gl2.h in this file"
4532#endif